This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo AuthSession
A universal library that provides an API to handle browser-based authentication.
AuthSession enables web browser-based authentication (for example, browser-based OAuth flows) in your app by utilizing WebBrowser and Crypto. For implementation details, refer to this reference, and for usage, see the Authentication guide.
Note:
AuthSessionenables general-purpose OAuth and OpenID Connect browser-based auth workflows. Where available, we recommend using a library supplied by your identity provider, as it will handle implementation details specific to that provider. For example, use@react-native-google-signin/google-signinfor Google authentication andreact-native-fbsdk-nextfor Facebook. For more information, see Authentication overview.
Installation
expo-cryptois a peer dependency and must be installed alongsideexpo-auth-session.
If you are installing this in an existing React Native app, make sure to install expo in your project.
Configuration
Are you using this library in an existing React Native app?
To use this library, you need to set up deep linking in your app by setting up a scheme. Use the uri-scheme CLI utility to easily add, remove, list, and open your URIs.
For example, to make your native app handle mycoolredirect://, run:
You should now be able to see a list of all your project's schemes by running:
You can test it to ensure it works like this:
Usage in standalone apps
To be able to deep link back into your app, you will need to set a scheme in your project's app config, and then build your standalone app (it can't be updated with an update). If you do not include a scheme, the authentication flow will complete, but it will be unable to pass the information back into your application and the user will have to manually exit the authentication modal (resulting in a canceled event).
Guides
The guides have moved: Authentication Guide.
How web browser based authentication flows work
The typical flow for browser-based authentication in mobile apps is as follows:
- Initiation: the user presses a sign in button
- Open web browser: the app opens up a web browser to the authentication provider sign in page. The url that is opened for the sign in page usually includes information to identify the app, and a URL to redirect to on success. Note: the web browser should share cookies with your system web browser so that users do not need to sign in again if they are already authenticated on the system browser — Expo's WebBrowser API takes care of this.
- Authentication provider redirects: upon successful authentication, the authentication provider should redirect back to the application by redirecting to URL provided by the app in the query parameters on the sign in page (read more about how linking works in mobile apps), provided that the URL is in the allowlist of allowed redirect URLs. Allowlisting redirect URLs is important to prevent malicious actors from pretending to be your application. The redirect includes data in the URL (such as user id and token), either in the location hash, query parameters, or both.
- App handles redirect: the redirect is handled by the app and data is parsed from the redirect URL.
Security considerations
- Never put any secret keys inside your application code, there is no secure way to do this! Instead, you should store your secret key(s) on a server and expose an endpoint that makes API calls for your client and passes the data back.
API
import * as AuthSession from 'expo-auth-session';
Hooks
Load an authorization request for a code. When the prompt method completes then the response will be fulfilled.
In order to close the popup window on web, you need to invoke
WebBrowser.maybeCompleteAuthSession(). See the GitHub example for more info.
If an Implicit grant flow was used, you can pass the response.params to TokenResponse.fromQueryParams()
to get a TokenResponse instance which you can use to easily refresh the token.
[AuthRequest | null, AuthSessionResult | null, (options: AuthRequestPromptOptions) => Promise<AuthSessionResult>]Returns a loaded request, a response, and a prompt method in a single array in the following order:
request- An instance ofAuthRequestthat can be used to prompt the user for authorization. This will benulluntil the auth request has finished loading.response- This isnulluntilpromptAsynchas been invoked. Once fulfilled it will return information about the authorization.promptAsync- When invoked, a web browser will open up and prompt the user for authentication. Accepts anAuthRequestPromptOptionsobject with options about how the prompt will execute.
Example
const [request, response, promptAsync] = useAuthRequest({ ... }, { ... });
Given an OpenID Connect issuer URL, this will fetch and return the DiscoveryDocument
(a collection of URLs) from the resource provider.
DiscoveryDocument | nullReturns null until the DiscoveryDocument has been fetched from the provided issuer URL.
Example
const discovery = useAutoDiscovery('https://example.com/auth');
Classes
Type: Class extends TokenRequest<AccessTokenRequestConfig> implements AccessTokenRequestConfig
Access token request. Exchange an authorization code for a user access token.
AccessTokenRequest Properties
GrantTypeAccessTokenRequest Methods
Headers{
clientId: string,
clientSecret: string | undefined,
code: string,
extraHeaders: Record<string, string> | undefined,
extraParams: Record<string, string> | undefined,
grantType: GrantType,
redirectUri: string,
scopes: string[] | undefined
}Type: Class extends ResponseError
Represents an authorization response error: Section 5.2. Often times providers will fail to return the proper error message for a given error code. This error method will add the missing description for more context on what went wrong.
AuthError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class implements Omit<AuthRequestConfig, 'state'>
Used to manage an authorization request according to the OAuth spec: Section 4.1.1. You can use this class directly for more info around the authorization.
Common use-cases:
- Parse a URL returned from the authorization server with
parseReturnUrlAsync(). - Get the built authorization URL with
makeAuthUrlAsync(). - Get a loaded JSON representation of the auth request with crypto state loaded with
getAuthRequestConfigAsync().
Example
// Create a request. const request = new AuthRequest({ ... }); // Prompt for an auth code const result = await request.promptAsync(discovery); // Get the URL to invoke const url = await request.makeAuthUrlAsync(discovery); // Get the URL to invoke const parsed = await request.parseReturnUrlAsync("<URL From Server>");
AuthRequest Properties
AuthRequest Methods
Load and return a valid auth request based on the input config.
Promise<AuthRequestConfig>Type: Class extends TokenRequest<RefreshTokenRequestConfig> implements RefreshTokenRequestConfig
Refresh request.
RefreshTokenRequest Properties
GrantTypeRefreshTokenRequest Methods
Headers{
clientId: string,
clientSecret: string | undefined,
extraHeaders: Record<string, string> | undefined,
extraParams: Record<string, string> | undefined,
grantType: GrantType,
refreshToken: string | undefined,
scopes: string[] | undefined
}Request Methods
Type: Class extends CodedError
ResponseError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class extends Request<RevokeTokenRequestConfig, boolean> implements RevokeTokenRequestConfig
Revocation request for a given token.
RevokeTokenRequest Methods
Headers{
clientId: string | undefined,
clientSecret: string | undefined,
extraHeaders: Record<string, string> | undefined,
token: string,
tokenTypeHint: TokenTypeHint | undefined
}Type: Class extends ResponseError
TokenError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class extends Request<T, TokenResponse> implements TokenRequestConfig
A generic token request.
TokenRequest Properties
GrantTypeTokenRequest Methods
HeadersType: Class implements TokenResponseConfig
Token Response.
TokenResponse Properties
TokenResponse Methods
TokenResponseConfigDetermines whether a token refresh request must be made to refresh the tokens
booleanMethods
Exchange an authorization code for an access token that can be used to get data from the provider.
Promise<TokenResponse>Returns a discovery document with a valid tokenEndpoint URL.
Fetch a DiscoveryDocument from a well-known resource provider that supports auto discovery.
Promise<DiscoveryDocument>Returns a discovery document that can be used for authentication.
Returns the current time in seconds.
numberDeprecated: Use
makeRedirectUri()instead.
Get the URL that your authentication provider needs to redirect to. For example: https://auth.expo.io/@your-username/your-app-slug. You can pass an additional path component to be appended to the default redirect URL.
Note This method will throw an exception if you're using the bare workflow on native.
stringExample
const url = AuthSession.getRedirectUrl('redirect'); // Managed: https://auth.expo.io/@your-username/your-app-slug/redirect // Web: https://localhost:19006/redirect
Append the well known resources path and OpenID connect discovery document path to a URL https://tools.ietf.org/html/rfc5785
stringBuild an AuthRequest and load it before returning.
Promise<AuthRequest>Returns an instance of AuthRequest that can be used to prompt the user for authorization.
Create a redirect url for the current platform and environment. You need to manually define the redirect that will be used in a bare workflow React Native app, or an Expo standalone app, this is because it cannot be inferred automatically.
- Web: Generates a path based on the current
window.location. For production web apps, you should hard code the URL as well. - Managed workflow: Uses the
schemeproperty of your app config. - Bare workflow: Will fallback to using the
nativeoption for bare workflow React Native apps.
stringThe redirectUri to use in an authentication request.
Example
const redirectUri = makeRedirectUri({ scheme: 'my-scheme', path: 'redirect' }); // Development Build: my-scheme://redirect // Expo Go: exp://127.0.0.1:8081/--/redirect // Web dev: https://localhost:19006/redirect // Web prod: https://yourwebsite.com/redirect const redirectUri2 = makeRedirectUri({ scheme: 'scheme2', preferLocalhost: true, isTripleSlashed: true, }); // Development Build: scheme2:/// // Expo Go: exp://localhost:8081 // Web dev: https://localhost:19006 // Web prod: https://yourwebsite.com
Refresh an access token.
- If the provider didn't return a
refresh_tokenthen the access token may not be refreshed. - If the provider didn't return a
expires_inthen it's assumed that the token does not expire. - Determine if a token needs to be refreshed via
TokenResponse.isTokenFresh()orshouldRefresh()on an instance ofTokenResponse.
Promise<TokenResponse>Returns a discovery document with a valid tokenEndpoint URL.
See: Section 6.
Utility method for resolving the discovery document from an issuer or object.
Promise<DiscoveryDocument>Revoke a token with a provider. This makes the token unusable, effectively requiring the user to login again.
Promise<boolean>Resolves to true when the revocation request completes. Rejects with an error if the provider does not expose a revocationEndpoint or the request fails. Many providers do not support this feature.
Types
Config used to exchange an authorization code for an access token.
See: Section 4.1.3
Type: TokenRequestConfig extended by:
Type: Pick<DiscoveryDocument, 'authorizationEndpoint'>
Options passed to the promptAsync() method of AuthRequests.
This can be used to configure how the web browser should look and behave.
Type: Omit<AuthSessionOpenOptions, 'windowFeatures'> extended by:
Object returned after an auth request has completed.
- If the user cancelled the authentication session by closing the browser, the result is
{ type: 'cancel' }. - If the authentication is dismissed manually with
AuthSession.dismiss(), the result is{ type: 'dismiss' }. - If the authentication flow is successful, the result is
{ type: 'success', params: Object, event: Object }. - If the authentication flow is returns an error, the result is
{ type: 'error', params: Object, error: string, event: Object }.
Type: object shaped as below:
Or object shaped as below:
URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier.
Type: string
OpenID Providers have metadata describing their configuration. ProviderMetadata
Type: Record<string, string | boolean | string[]> ProviderMetadataEndpoints extended by:
Config used to request a token refresh, or code exchange.
See: Section 6
Type: TokenRequestConfig extended by:
Config used to request a token refresh, revocation, or code exchange.
Enums
CodeChallengeMethod.Plain = "plain"This should not be used. When used, the code verifier will be sent to the server as-is.
Grant type values used in dynamic client registration and auth requests.
See: Appendix A.10
GrantType.AuthorizationCode = "authorization_code"Used for exchanging an authorization code for one or more tokens.
GrantType.ClientCredentials = "client_credentials"Used for client credentials flow.
GrantType.RefreshToken = "refresh_token"Used when exchanging a refresh token for a new token.
Informs the server if the user should be prompted to login or consent again. This can be used to present a dialog for switching accounts after the user has already been logged in. You should use this in favor of clearing cookies (which is mostly not possible on iOS).
See: Section 3.1.2.1.
Prompt.Consent = "consent"Server should prompt the user for consent before returning information to the client.
If it cannot obtain consent, it must return an error, typically consent_required.
Prompt.Login = "login"The server should prompt the user to reauthenticate.
If it cannot reauthenticate the End-User, it must return an error, typically login_required.
Prompt.None = "none"Server must not display any auth or consent UI. Can be used to check for existing auth or consent.
An error is returned if a user isn't already authenticated or the client doesn't have pre-configured consent for the requested claims, or does not fulfill other conditions for processing the request.
The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6.
The client informs the authorization server of the desired grant type by using the response type.
See: Section 3.1.1.
ResponseType.IdToken = "id_token"A custom registered type for getting an id_token from Google OAuth.
ResponseType.Token = "token"For requesting an access token (implicit grant) as described by Section 4.2.1.
A hint about the type of the token submitted for revocation. If not included then the server should attempt to deduce the token type.
See: Section 2.1
Advanced usage
Filtering out AuthSession events in Linking handlers
There are many reasons why you might want to handle inbound links into your app, such as push notifications or just regular deep linking (you can read more about this in the Linking); authentication redirects are only one type of deep link, and AuthSession handles these particular links for you. In your own Linking.addEventListener handlers, you can filter out deep links that are handled by AuthSession by checking if the URL includes the +expo-auth-session string — if it does, you can ignore it. This works because AuthSession adds +expo-auth-session to the default returnUrl; however, if you provide your own returnUrl, you may want to consider adding a similar identifier to enable you to filter out AuthSession events from other handlers.
With React Navigation
If you are using deep linking with React Navigation, filtering through Linking.addEventListener will not be sufficient because deep linking is handled differently. Instead, to filter these events, add a custom getStateFromPath function to your linking configuration, and then filter by URL in the same way as described above.