Social sign-in for native and mobile apps
Overview
This page covers how to implement social sign-in for native applications via OIDC and OAuth 2.0. The user interaction looks like this:
- The user is presented with a login or registration screen that includes a social sign-in button.
- The user clicks the social sign-in button. A browser window opens (using ASWebAuthenticationSession on iOS or Custom Tabs on Android).
- The user authenticates with the identity provider and grants the application access to profile information.
- The user is redirected back to the application and is logged in.
Apple and Google support a more tightly integrated login experience for native apps. See the documentation on Apple social sign-in and Google social sign-in for more information.
The native app authentication flow
From a high level, the native app initializes a login or registration flow and receives the first part of the session token exchange code from the Ory Network. After the user performed the social sign-in, the user is redirected back to the native application via an iOS Universal Link or Android App Link. The native application then exchanges the session token exchange code for a session token.
As part of this flow, Ory will redirect the browser to a callback. In this demo, the redirect URL
http://localhost:19006/Callback is used. Please ensure that this redirect URL is allowed. Go
to Branding → Browser redirects in the Ory Console to allow it.
The flow looks like this:
Implementation
The following sections describe how to implement the native app authentication flow. The code examples are written in TypeScript for React Native. The steps refer to the steps in the flow diagram above.
Steps 1-5: Create an API flow with return_session_token_exchange_code=true
The user opens the login screen (1) and the native application initializes a login or registration flow through the Ory Network APIs (2) with the following parameters:
- The flow is of type
api. - The
return_toparameter is set to the URL of the native application. This URL is used to redirect the user back to the app after the social sign-in. - The
return_session_token_exchange_codeparameter is set totrueto receive the session token exchange code in the response (3).
// ...
const initializeFlow = () =>
newOrySdk(project)
.createNativeLoginFlow({
aal: route.params.aal,
refresh: route.params.refresh,
xSessionToken: sessionToken,
// If you do use social sign in, please add the following URLs to your allowed return to URLs.
// If you the app is running on an emulator or physical device: exp://localhost:8081
// If you are using the web version: http://localhost:19006 (or whatever port you are using)
// If that does not work, please see the documentation of makeRedirectURI for more information: https://docs.expo.dev/versions/latest/sdk/auth-session/#authsessionmakeredirecturioptions
// If you don't use Social sign in, you can comment out the following line.
returnTo: AuthSession.makeRedirectUri({
preferLocalhost: true,
path: "/Callback",
}),
returnSessionTokenExchangeCode: true,
})
.then((f) => setFlow(f))
.catch(logSDKError)
const refetchFlow = () =>
newOrySdk(project)
.getLoginFlow({ id: flow!.id })
.then((f) =>
setFlow({
...flow,
...f,
// The GET response may not include the exchange code, and the
// client-fetch deserializer explicitly sets missing fields to
// undefined which would override the original value via spread.
session_token_exchange_code:
f.session_token_exchange_code ??
flow?.session_token_exchange_code,
}),
)
.catch(logSDKError)
// When the component is mounted, we initialize a new use login flow:
useFocusEffect(
React.useCallback(() => {
initializeFlow()
return () => {
setFlow(undefined)
}
}, [project]),
)
const setSessionAndRedirect = (session: SessionContext) => {
setSession(session)
setTimeout(() => {
navigation.navigate("Home")
}, 100)
}
// This will update the login flow with the user provided input:
const onSubmit = (payload: UpdateLoginFlowBody) =>
flow
? newOrySdk(project)
.updateLoginFlow({
flow: flow.id,
updateLoginFlowBody: payload,
xSessionToken: sessionToken,
})
.then((data) => {
// For refresh/aal2 logins, Kratos may not return a new session_token
// (the token is unchanged). In that case, preserve the existing token.
const result: SessionContext = {
session: data.session,
session_token: data.session_token || sessionToken || "",
}
return result
})
// Looks like everything worked and we have a session!
.then(setSessionAndRedirect)
.catch(
handleFormSubmitError(
flow,
setFlow,
initializeFlow,
setSessionAndRedirect,
refetchFlow,
),
)
: Promise.resolve()
return (
<AuthLayout>
<StyledCard>
<AuthSubTitle>Sign in to your account</AuthSubTitle>
<SelfServiceFlow flow={flow} onSubmit={onSubmit} />
</StyledCard>
<NavigationCard
testID="nav-signup"
description="Need an account?"
cta="Sign up!"
onPress={() => navigation.navigate("Registration")}
/>
<NavigationCard
testID="nav-recover"
description="Forgot your password?"
cta="Reset it!"
onPress={() => navigation.navigate("Recovery")}
/>
<ProjectPicker />
</AuthLayout>
)
}
export default Login
Upon rendering the form, the user selects the specific social sign-in provider (4). The native application submits the form to the Ory Network (5).
Steps 6-12: Open the identity provider authentication URL in a browser
Ory Network returns a 422 status code if the user needs to perform a social sign-in from a flow of type api (6). The response
contains the URL of the identity provider in the redirect_browser_to field.
// ...
case 422:
console.log(
"The server responded with a 422 error, which indicates that to complete this action, the user needs to fulfil additional steps.",
JSON.stringify(err.response.data, null, 2),
)
// ...
WebBrowser.openAuthSessionAsync
opens a browser tab for authentication for the specified url (7+8). Implementations in other languages and frameworks may vary.
// ...
const result = await WebBrowser.openAuthSessionAsync(
url,
AuthSession.makeRedirectUri({
preferLocalhost: true,
path: "/Callback",
}),
)
// ...
The user authenticates with the identity provider and grants the application access to profile information (9). The identity provider then issues a redirect to the Ory Network callback URL (10), which the browser follows (11).
Steps 12-14: Exchange the session token exchange code for a session token
Finally, Ory Network issues a session for the user and redirects the browser to the application's return_to URL (12). The native
application receives the second part of the session token exchange code in the code URL query parameter. In the example below,
the call to
WebBrowser.maybeCompleteAuthSession
is used to close the browser tab and return the control flow to the code that awaited the call to
WebBrowser.openAuthSessionAsync.
// ...
const Callback = (props: Props) => {
useEffect(() => {
WebBrowser.maybeCompleteAuthSession({
skipRedirectCheck: false,
})
}, [])
return (
<View>
{props.route.params?.code ? (
<Text>
Hello Callback! Your code is <Text style={{ fontFamily: "monospace" }}>{props.route.params?.code}</Text>
</Text>
) : (
// ...
The native application then exchanges the session token exchange code for a session token (13) using the first part of the code
returned from the flow initialization, and the second part of the code returned from the return_to query parameter.
The code can be exchanged within one hour after the flow was created. After the first successful exchange, the code works for five
more seconds, so that a repeated exchange, for example after a double tap, returns the same session token. After that, or once the
hour has passed, the exchange returns 404 Not Found, and the user has to sign in again.
import {
ContinueWith,
ErrorBrowserLocationChangeRequired,
ExchangeSessionTokenRequest,
GenericError,
instanceOfUiNodeInputAttributes,
LoginFlow,
RecoveryFlow,
RegistrationFlow,
SettingsFlow,
UiNode,
VerificationFlow,
} from "@ory/client-fetch"
import * as AuthSession from "expo-auth-session"
import * as WebBrowser from "expo-web-browser"
import { showMessage } from "react-native-flash-message"
import { SessionContext } from "./auth"
import { logSDKError, HttpError, isResponseError, parseResponseError } from "./errors"
import { newOrySdk } from "./sdk"
type Flow = LoginFlow | RegistrationFlow | VerificationFlow | RecoveryFlow
export function camelize<T>(str: string) {
return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase()) as keyof T
}
export function getNodeId({ attributes }: UiNode) {
if (instanceOfUiNodeInputAttributes(attributes)) {
return attributes.name
} else {
return attributes.id
}
}
export function getNodeValue({ attributes }: UiNode) {
if (instanceOfUiNodeInputAttributes(attributes)) {
return attributes.value
}
return ""
}
export const getNodeTitle = ({ attributes, meta }: UiNode): string => {
if (instanceOfUiNodeInputAttributes(attributes)) {
if (meta?.label?.text) {
return meta.label.text
}
return attributes.name
}
if (meta?.label?.text) {
return meta.label.text
}
return ""
}
function isErrorGeneric(data: unknown): data is { error: GenericError } {
return (
typeof data === "object" &&
data !== null &&
"error" in data &&
typeof data.error === "object"
)
}
function isRedirectBrowserToError(
data: unknown,
): data is ErrorBrowserLocationChangeRequired {
return (
typeof data === "object" && data !== null && "redirect_browser_to" in data
)
}
export function handleFormSubmitError<
T extends RegistrationFlow | LoginFlow | VerificationFlow | SettingsFlow | undefined,
>(
flow: T,
setFlow: (p: T) => void,
initializeFlow: (fId?: string) => void,
setSession: (p: SessionContext) => void,
refetchFlow: () => Promise<void>,
logout?: () => void,
handleContinueWith?: (c: ContinueWith[]) => Promise<void>,
) {
// Inner function that handles HttpError
const handleHttpError = (err: HttpError) => {
logSDKError(err)
if (err.response) {
switch (err.response.status) {
case 400:
if (isErrorGeneric(err.response.data)) {
const ge = err.response.data.error
showMessage({
message: `${ge.message}: ${ge.reason}`,
type: "danger",
})
return Promise.resolve()
}
console.debug(
"Form validation failed:",
JSON.stringify(err.response.data),
)
setFlow(err.response.data as T)
return Promise.resolve()
case 404:
console.debug("Flow could not be found, re-initializing the flow.")
initializeFlow()
return Promise.resolve()
case 410: {
// This happens when the flow is, for example, expired or was deleted.
// Sometimes, Ory returns a replacement flow here
console.debug("The flow expired, re-initializing the flow.")
const errorData = err.response.data as { error?: { details?: { continue_with?: ContinueWith[] } } } | undefined
const continueWith = errorData?.error?.details?.continue_with
if (Array.isArray(continueWith) && handleContinueWith) {
return handleContinueWith(continueWith)
}
initializeFlow()
return Promise.resolve()
}
case 403:
case 401:
if (!logout) {
console.error(
`Received unexpected 401/403 status code: `,
err,
err.response.data as unknown,
)
return Promise.resolve()
}
// This happens when the privileged session is expired but the user tried
// to modify a privileged field (e.g. change the password).
console.warn(
"The server indicated that this action is not allowed for you. The most likely cause of that is that you modified a privileged field (e.g. your password) but your Ory Identities Login Session is too old.",
)
showMessage({
message: "Please re-authenticate before making these changes.",
type: "warning",
})
logout()
return Promise.resolve()
case 422:
console.log(
"The server responded with a 422 error, which indicates that to complete this action, the user needs to fulfil additional steps.",
JSON.stringify(err.response.data, null, 2),
)
if (
isRedirectBrowserToError(err.response.data) &&
err.response.data.redirect_browser_to
) {
handleRedirectBrowserTo(
err.response.data.redirect_browser_to,
flow as any,
setSession,
refetchFlow,
)
}
return Promise.resolve()
}
}
return Promise.resolve()
}
// Return async function that handles both ResponseError and HttpError
return async (err: unknown) => {
if (isResponseError(err)) {
const httpError = await parseResponseError(err)
return handleHttpError(httpError)
}
return handleHttpError(err as HttpError)
}
}
async function handleRedirectBrowserTo(
url: string,
flow: LoginFlow | RegistrationFlow | SettingsFlow | undefined,
setSession: (p: SessionContext) => void,
refetchFlow: () => Promise<void>,
) {
const fetchToken = (params: ExchangeSessionTokenRequest) =>
newOrySdk("").exchangeSessionToken(params)
// ...
Finally, the native application stores the session token in the secure storage (14) and redirects the user to the home screen.
// ...
const setToken = (res: Awaited<ReturnType<typeof fetchToken>>) =>
res?.session_token &&
setSession({
session: res.session,
session_token: res.session_token,
})
// ...
ID token nonce
This section applies when your app gets an ID token from the Google or Apple SDK and submits it to Ory as id_token, as described
in Google social sign-in and
Apple social sign-in.
When a provider that accepts ID tokens is configured, every login and registration flow contains an id_token_nonce:
{
"id": "0b1f6b0c-3b1e-4c0a-9d0e-3f5f4b6a7c8d",
"type": "api",
"id_token_nonce": "5c4f8d3e-9a1b-4e6f-8b2a-7d3c1e0f9a4b"
}
Use it like this:
- Create the login or registration flow.
- Pass
id_token_nonceto the provider SDK as the nonce. Don't hash or change it. - Submit the
id_tokento the same flow, together with the nonce asid_token_nonce.
Require the flow's nonce
By default, Ory compares the nonce in the ID token to the id_token_nonce value your app submits with it. This keeps apps working
that generate their own nonce.
To accept an ID token only in the flow it was requested for, and only once, turn on the oidc_server_issued_id_token_nonce
feature flag. Enable the flag in the Ory Console under Project settings → Advanced, or with the Ory CLI:
ory patch project --project <project-id> --workspace <workspace-id> \
--replace '/services/identity/config/feature_flags/oidc_server_issued_id_token_nonce=true'
Self-hosted deployments set feature_flags.oidc_server_issued_id_token_nonce to true in the Ory Kratos configuration.
With the flag on:
- The ID token must contain the
id_token_nonceof the flow it is submitted to. Theid_token_noncevalue in the request is ignored. - An ID token without a nonce is rejected. This includes Google ID tokens from SDKs that don't send a nonce.
- A nonce signs in once. After a successful sign-in, or after a sign-in that an Ory Action rejected, create a new flow and request a new ID token.
- You can submit the same ID token to the same flow again when Ory answers with a validation error, for example to add missing traits during registration.
When Ory rejects an ID token for its nonce, the response has the status 403 and the error id oidc_id_token_nonce_rejected.
Create a new flow and request a new ID token with that flow's id_token_nonce.
Turn the flag on only after every released version of your app reads id_token_nonce from the flow. Versions that generate their
own nonce can no longer sign in with the Google or Apple SDK once the flag is on.