Expo

Get Started
API Reference

AuthSession

AuthSession is the easiest way to add web browser based authentication (for example, browser-based OAuth flows) to your app, built on top of WebBrowser, Crypto, and Random. If you would like to understand how it does this, read this document from top to bottom. If you just want to use it, jump to the Authentication Guide.

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

Installation

expo-random is a peer dependency and must be installed alongside expo-auth-session.
Terminal
→ expo install expo-auth-session expo-random

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

In bare-workflow you can use the uri-scheme package to easily add, remove, list, and open your URIs.
To make your native app handle mycoolredirect:// simply run:
Terminal
→ npx uri-scheme add mycoolredirect

You should now be able to see a list of all your project's schemes by running:
Terminal
→ npx uri-scheme list

You can test it to ensure it works like this:
Terminal
# Rebuild the native apps, be sure to use an emulated device
→ yarn ios
→ yarn android

# Open a URI scheme
→ npx uri-scheme open mycoolredirect://some/redirect

app.json
{
  "expo": {
    "scheme": "mycoolredirect"
  }
}
In order to be able to deep link back into your app, you will need to set a scheme in your project app.config.js, or app.json, 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 cancelled event).

The guides have moved: Authentication Guide.

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.

The auth.expo.io proxy is only used when startAsync is called, or when useProxy: true is passed to the promptAsync() method of an AuthRequest.

AuthSession handles most of the app-side responsibilities for you:
  • It opens the sign in URL for your authentication provider (authUrl, you must provide it) in a web browser that shares cookies with your system browser.
  • It handles success redirects and extracts all of the data encoded in the URL.
  • It handles failures and provides information to you about what went wrong.

Additionally, AuthSession simplifies setting up authorized redirect URLs by using an Expo service that sits between you and your authentication provider (read Security considerations for caveats). This is particularly valuable with Expo because your app can live at various URLs. In development, you can have a tunnel URL, a lan URL, and a localhost URL. The tunnel URL on your machine for the same app will be different from a co-worker's machine. When you publish your app, that will be another URL that you need to allowlist. If you have multiple environments that you publish to, each of those will also need to be allowlisted. AuthSession gets around this by only having you allowlist one URL with your authentication provider: https://auth.expo.io/@your-username/your-app-slug. When authentication is successful, your authentication provider will redirect to that Expo Auth URL, and then the Expo Auth service will redirect back to your application. If the URL that the auth service is redirecting back to does not match the published URL for the app or the standalone app scheme (eg: exp://expo.dev/@your-username/your-app-slug, or yourscheme://), then it will show a warning page before asking the user to sign in. This means that in development you will see this warning page when you sign in, a small price to pay for the convenience.
How does this work? When you open an authentication session with AuthSession, it first visits https://auth.expo.io/@your-username/your-app-slug/start and passes in the authUrl and returnUrl (the URL to redirect back to your application) in the query parameters. The Expo Auth service saves away the returnUrl (and if it is not a published URL or your registered custom theme, shows a warning page) and then sends the user off to the authUrl. When the authentication provider redirects back to https://auth.expo.io/@your-username/your-app-slug on success, the Expo Auth services redirects back to the returnUrl that was provided on initiating the authentication flow.

If you are authenticating with a popular social provider, when you are ready to ship to production you should be sure that you do not directly request the access token for the user. Instead, most providers give an option to request a one-time code that can be combined with a secret key to request an access token. For an example of this flow, see the Confirming Identity section in the Facebook Login documentation.
Never put any secret keys inside of your app, 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.

import * as AuthSession from 'expo-auth-session';

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 Identity 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.

Example

const [request, response, promptAsync] = useAuthRequest({ ... }, { ... });

  • [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 of AuthRequest that can be used to prompt the user for authorization. This will be null until the auth request has finished loading.
  • response - This is null until promptAsync has 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 an AuthRequestPromptOptions object with options about how the prompt will execute. You can use this to enable the Expo proxy service auth.expo.io.

  • issuerOrDiscovery (IssuerOrDiscovery) - URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier.

Given an OpenID Connect issuer URL, this will fetch and return the DiscoveryDocument (a collection of URLs) from the resource provider.

Example

const discovery = useAutoDiscovery('https://example.com/auth');

Returns null until the DiscoveryDocument has been fetched from the provided issuer URL.

Type: Class extends TokenRequest<AccessTokenRequestConfig> implements AccessTokenRequestConfig

Access token request. Exchange an authorization code for a user access token.

Section 4.1.3


  • Type: GrantType



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.


  • Type: string


  • Optional • Type: string

    Used to assist the client developer in understanding the error that occurred.


  • Optional • Type: any


  • Type: string


  • Type: string


  • Type: Record<string, string>

    Raw results of the error.


  • Optional • Type: string


  • Optional • Type: string

    Required only if state is used in the initial request


  • Optional • Type: string

    A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.


  • Optional • Type: (err: Error, stackTraces: CallSite[]) => any


  • Type: number


  • targetObject (object)
  • constructorOpt? (Function)

Create .stack property on a target object


Type: Class implements Omit<AuthRequestConfig, 'state'>

Used to manage an authorization request according to the OAuth spec: [Section 4.1.1][https://tools.ietf.org/html/rfc6749#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, { useProxy: true });

// Get the URL to invoke
const url = await request.makeAuthUrlAsync(discovery);

// Get the URL to invoke
const parsed = await request.parseReturnUrlAsync("<URL From Server>");



Type: Class extends ResponseError

Section 4.1.2.1


  • Type: string


  • Optional • Type: string

    Used to assist the client developer in understanding the error that occurred.


  • Optional • Type: any


  • Type: string


  • Type: string


  • Type: Record<string, string>

    Raw results of the error.


  • Optional • Type: string


  • Optional • Type: string

    A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.


  • Optional • Type: (err: Error, stackTraces: CallSite[]) => any


  • Type: number


  • targetObject (object)
  • constructorOpt? (Function)

Create .stack property on a target object


Type: Class implements TokenResponseConfig

Token Response.

Section 5.1


  • params (Record<string, any>)

Creates a TokenResponse from query parameters returned from an AuthRequest.


Determines whether a token refresh request must be made to refresh the tokens

  • boolean

Cancels an active AuthSession if there is one. No return value, but if there is an active AuthSession then the Promise returned by the AuthSession.startAsync() that initiated it resolves to { type: 'dismiss' }.


Exchange an authorization code for an access token that can be used to get data from the provider.

Returns a discovery document with a valid tokenEndpoint URL.


  • issuer (string) - An Issuer URL to fetch from.

Fetch a DiscoveryDocument from a well-known resource provider that supports auto discovery.

Returns a discovery document that can be used for authentication.


  • config (Pick<TokenResponse, 'accessToken'>) - The accessToken for a user, returned from a code exchange or auth request.
  • discovery (Pick<DiscoveryDocument, 'userInfoEndpoint'>) - The userInfoEndpoint for a provider.

Fetch generic user info from the provider's OpenID Connect userInfoEndpoint (if supported).

See: UserInfo.


  • size (number)

Digest a random string with hex encoding, useful for creating nonces.


Deprecated. Use makeRedirectUri({ path, useProxy }) instead.

  • path? (string)

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.

Example

const url = AuthSession.getRedirectUrl('redirect');

// Managed: https://auth.expo.io/@your-username/your-app-slug/redirect
// Web: https://localhost:19006/redirect

  • string

Build an AuthRequest and load it before returning.

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 scheme property of your app.config.js or app.json.
    • Proxy: Uses auth.expo.io as the base URL for the path. This only works in Expo Go and standalone environments.
  • Bare workflow: Will fallback to using the native option for bare workflow React Native apps.

Example

const redirectUri = makeRedirectUri({
  scheme: 'my-scheme',
  path: 'redirect'
});
// Custom app: my-scheme://redirect
// Expo Go: exp://127.0.0.1:19000/--/redirect
// Web dev: https://localhost:19006/redirect
// Web prod: https://yourwebsite.com/redirect

const redirectUri2 = makeRedirectUri({
  scheme: 'scheme2',
  preferLocalhost: true,
  isTripleSlashed: true,
});
// Custom app: scheme2:///
// Expo Go: exp://localhost:19000
// Web dev: https://localhost:19006
// Web prod: https://yourwebsite.com

const redirectUri3 = makeRedirectUri({
  useProxy: true,
});
// Custom app: https://auth.expo.io/@username/slug
// Expo Go: https://auth.expo.io/@username/slug
// Web dev: https://localhost:19006
// Web prod: https://yourwebsite.com

  • string

The redirectUri to use in an authentication request.


Refresh an access token.

  • If the provider didn't return a refresh_token then the access token may not be refreshed.
  • If the provider didn't return a expires_in then it's assumed that the token does not expire.
  • Determine if a token needs to be refreshed via TokenResponse.isTokenFresh() or shouldRefresh() on an instance of TokenResponse.
See: Section 6.

Returns a discovery document with a valid tokenEndpoint URL.


Utility method for resolving the discovery document from an issuer or object.


Revoke a token with a provider. This makes the token unusable, effectively requiring the user to login again.

Returns a discovery document with a valid revocationEndpoint URL. Many providers do not support this feature.


Initiate a proxied authentication session with the given options. Only one AuthSession can be active at any given time in your application. If you attempt to open a second session while one is still in progress, the second session will return a value to indicate that AuthSession is locked.

Returns a Promise that resolves to an AuthSessionResult object.

Options passed to the promptAsync() method of AuthRequests. This can be used to configure how the web browser should look and behave.

Omit<WebBrowserOpenOptions, 'windowFeatures'> extended by:

NameTypeDescription
projectNameForProxy
(optional)
stringProject name to use for the `auth.expo.io` proxy when useProxy is true.
proxyOptions
(optional)
Omit<CreateURLOptions, 'queryParams'> & { path: string }URL options to be used when creating the redirect URL for the auth proxy.
url
(optional)
stringURL to open when prompting the user. This usually should be defined internally and left undefined in most cases.
useProxy
(optional)
booleanShould the authentication request use the Expo proxy service auth.expo.io.

Default: false
windowFeatures
(optional)
WebBrowserWindowFeatures
Web Only

Features to use with window.open().

NameTypeDescription
authUrlstringThe URL that points to the sign in page that you would like to open the user to.
projectNameForProxy
(optional)
stringProject name to use for the `auth.expo.io` proxy.
returnUrl
(optional)
stringThe URL to return to the application. In managed apps, it's optional and defaults to output of Linking.createURL('expo-auth-session', params) call with scheme and queryParams params. However, in the bare app, it's required - AuthSession needs to know where to wait for the response. Hence, this method will throw an exception, if you don't provide returnUrl.
showInRecents
(optional)
boolean
Android Only

A boolean determining whether browsed website should be shown as separate entry in Android recents/multitasking view.

Default: false

Options passed to makeRedirectUriAsync.

NameTypeDescription
isTripleSlashed
(optional)
booleanShould the URI be triple slashed scheme:///path or double slashed scheme://path. Defaults to false. Passed to Linking.createURL() when useProxy is false.
native
(optional)
stringManual scheme to use in Bare and Standalone native app contexts. Takes precedence over all other properties. You must define the URI scheme that will be used in a custom built native application or standalone Expo application. The value should conform to your native app's URI schemes. You can see conformance with npx uri-scheme list.
path
(optional)
stringOptional path to append to a URI. This will not be added to native.
preferLocalhost
(optional)
booleanAttempt to convert the Expo server IP address to localhost. This is useful for testing when your IP changes often, this will only work for iOS simulator.

Default: false
projectNameForProxy
(optional)
stringProject name to use for the `auth.expo.io` proxy when useProxy is true.
queryParams
(optional)
Record<string, string | undefined>Optional native scheme to use when proxy is disabled. URI protocol <scheme>:// that must be built into your native app. Passed to Linking.createURL() when useProxy is false.
scheme
(optional)
stringURI protocol <scheme>:// that must be built into your native app. Passed to Linking.createURL() when useProxy is false.
useProxy
(optional)
booleanShould use the `auth.expo.io` proxy. This is useful for testing managed native apps that require a custom URI scheme.

Default: false

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 }.
  • If you call AuthSession.startAsync() more than once before the first call has returned, the result is { type: 'locked' }, because only one AuthSession can be in progress at any time.
NameTypeDescription
type'cancel' | 'dismiss' | 'opened' | 'locked'How the auth completed.
NameTypeDescription
authenticationTokenResponse | nullReturned when the auth finishes with an access_token property.
error
(optional)
AuthError | nullPossible error if the auth failed with type error.
errorCodestring | null
Deprecated. Legacy error code query param, use error instead.
paramsRecord<string, string>Query params from the url as an object.
type'error' | 'success'How the auth completed.
urlstringAuth URL that was opened

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

Record<string, string | boolean | string[]>ProviderMetadataEndpoints extended by:

NameTypeDescription
backchannel_logout_session_supported
(optional)
boolean-
backchannel_logout_supported
(optional)
boolean-
check_session_iframe
(optional)
string-
claim_types_supported
(optional)
string[]a list of the Claim Types that the OpenID Provider supports.
claims_locales_supported
(optional)
string[]Languages and scripts supported for values in Claims being returned.
claims_parameter_supported
(optional)
booleanBoolean value specifying whether the OP supports use of the claims parameter, with true indicating support.

Default: false
claims_supported
(optional)
string[]a list of the Claim Names of the Claims that the OpenID Provider may be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
code_challenge_methods_supported
(optional)
CodeChallengeMethod[]-
display_values_supported
(optional)
string[]a list of the display parameter values that the OpenID Provider supports.
frontchannel_logout_session_supported
(optional)
boolean-
frontchannel_logout_supported
(optional)
boolean-
grant_types_supported
(optional)
string[]JSON array containing a list of the OAuth 2.0 Grant Type values that this OP supports. Dynamic OpenID Providers MUST support the authorization_code and implicit Grant Type values and MAY support other Grant Types. If omitted, the default value is ["authorization_code", "implicit"].
id_token_signing_alg_values_supported
(optional)
string[]JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT. The algorithm RS256 MUST be included.
jwks_uri
(optional)
stringURL of the OP's JSON Web Key Set JWK document.
op_policy_uri
(optional)
stringURL that the OpenID Provider provides to the person registering the Client to read about the OP's requirements on how the Relying Party can use the data provided by the OP. The registration process SHOULD display this URL to the person registering the Client if it is given.
op_tos_uri
(optional)
stringURL that the OpenID Provider provides to the person registering the Client to read about OpenID Provider's terms of service. The registration process should display this URL to the person registering the Client if it is given.
request_parameter_supported
(optional)
booleanBoolean value specifying whether the OP supports use of the request parameter, with true indicating support.

Default: false
request_uri_parameter_supported
(optional)
booleanWhether the OP supports use of the request_uri parameter, with true indicating support.

Default: true
require_request_uri_registration
(optional)
booleanWhether the OP requires any request_uri values used to be pre-registered using the request_uris registration parameter. Pre-registration is required when the value is true.

Default: false
response_modes_supported
(optional)
string[]JSON array containing a list of the OAuth 2.0 response_mode values that this OP supports, as specified in OAuth 2.0 Multiple Response Type Encoding Practices. If omitted, the default for Dynamic OpenID Providers is ["query", "fragment"].
response_types_supported
(optional)
string[]JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers must support the code, id_token, and the token id_token Response Type values
scopes_supported
(optional)
string[]JSON array containing a list of the OAuth 2.0 RFC6749 scope values that this server supports.
service_documentation
(optional)
stringURL of a page containing human-readable information that developers might want or need to know when using the OpenID Provider. In particular, if the OpenID Provider does not support Dynamic Client Registration, then information on how to register Clients needs to be provided in this documentation.
subject_types_supported
(optional)
string[]JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
token_endpoint_auth_methods_supported
(optional)
('client_secret_post' | 'client_secret_basic' | 'client_secret_jwt' | 'private_key_jwt' | string)[]A list of Client authentication methods supported by this Token Endpoint. If omitted, the default is ['client_secret_basic']
ui_locales_supported
(optional)
string[]Languages and scripts supported for the user interface, represented as a JSON array of BCP47 language tag values.

Access token type.

string - Acceptable values are: 'bearer', 'mac'.

Extends: TokenRequestConfig

Config used to exchange an authorization code for an access token.

NameTypeDescription
codestringThe authorization code received from the authorization server.
redirectUristringIf the redirectUri parameter was included in the AuthRequest, then it must be supplied here as well.Section 3.1.2

Represents an OAuth authorization request as JSON.

NameTypeDescription
clientIdstringA unique string representing the registration information provided by the client. The client identifier is not a secret; it is exposed to the resource owner and shouldn't be used alone for client authentication.The client identifier is unique to the authorization server. Section 2.2
clientSecret
(optional)
stringClient secret supplied by an auth provider. There is no secure way to store this on the client.Section 2.3.1
codeChallenge
(optional)
stringDerived from the code verifier by using the CodeChallengeMethod.Section 4.2
codeChallengeMethod
(optional)
CodeChallengeMethodMethod used to generate the code challenge. You should never use Plain as it's not good enough for secure verification.

Default: CodeChallengeMethod.S256
extraParams
(optional)
Record<string, string>Extra query params that'll be added to the query string.
prompt
(optional)
PromptInforms 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.Section 3.1.2.1
redirectUristringAfter completing an interaction with a resource owner the server will redirect to this URI. Learn more about linking in Expo.Section 3.1.2
responseType
(optional)
stringSpecifies what is returned from the authorization server.Section 3.1.1

Default: ResponseType.Code
scopes
(optional)
string[]List of strings to request access to.Section 3.3
state
(optional)
stringUsed for protection against Cross-Site Request Forgery.
usePKCE
(optional)
booleanShould use Proof Key for Code Exchange.

Default: true

NameTypeDescription
authorizationEndpoint
(optional)
stringUsed to interact with the resource owner and obtain an authorization grant.Section 3.1
discoveryDocument
(optional)
ProviderMetadataAll metadata about the provider.
endSessionEndpoint
(optional)
stringURL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP.OPMetadata
registrationEndpoint
(optional)
stringURL of the OP's Dynamic Client Registration Endpoint.
revocationEndpoint
(optional)
stringUsed to revoke a token (generally for signing out). The spec requires a revocation endpoint, but some providers (like Spotify) do not support one.Section 2.1
tokenEndpoint
(optional)
stringUsed by the client to obtain an access token by presenting its authorization grant or refresh token. The token endpoint is used with every authorization grant except for the implicit grant type (since an access token is issued directly).Section 3.2
userInfoEndpoint
(optional)
stringURL of the OP's UserInfo Endpoint used to return info about the authenticated user.UserInfo

Extends: ProviderAuthRequestConfig

NameTypeDescription
androidClientId
(optional)
string-
expoClientId
(optional)
string-
iosClientId
(optional)
string-
webClientId
(optional)
string-

Extends: ProviderAuthRequestConfig

NameTypeDescription
androidClientId
(optional)
stringAndroid native client ID for use in standalone, and bare workflow.This Google Client ID must be setup as follows:
  • Application Type: Android Application
  • Give it a name (e.g. "Android App").
  • Package name: Must match the value of android.package in your app.json.
  • Your app needs to conform to the URI scheme matching your android.package (ex. com.myname.mycoolapp:/).
    • Standalone: Automatically added, do nothing.
    • Bare workflow: Run npx uri-scheme add <your android.package> --android
  • Signing-certificate fingerprint:
    • Run expo credentials:manager -p android then select "Update upload Keystore" -> "Generate new keystore" -> "Go back to experience overview"
    • Copy your "Google Certificate Fingerprint", it will output a string that looks like A1:B2:C3 but longer.
  • To test this you can:
    1. Eject to bare: expo eject and run yarn ios
    2. Build a production IPA: expo build:android
expoClientId
(optional)
stringProxy client ID for use in the Expo client on iOS and Android.This Google Client ID must be setup as follows:
iosClientId
(optional)
stringiOS native client ID for use in standalone, bare workflow, and custom clients.This Google Client ID must be setup as follows:
  • Application Type: iOS Application
  • Give it a name (e.g. "iOS App").
  • Bundle ID: Must match the value of ios.bundleIdentifier in your app.json.
  • Your app needs to conform to the URI scheme matching your bundle identifier.
    • Standalone: Automatically added, do nothing.
    • Bare workflow: Run npx uri-scheme add <your bundle id> --ios
  • To test this you can:
    1. Eject to bare: expo eject and run yarn ios
    2. Create a custom client: expo client:ios
    3. Build a production IPA: expo build:ios
  • Whenever you change the values in app.json you'll need to rebuild the native app.
language
(optional)
stringLanguage code ISO 3166-1 alpha-2 region code, such as 'it' or 'pt-PT'.
loginHint
(optional)
stringIf the user's email address is known ahead of time, it can be supplied to be the default option. If the user has approved access for this app in the past then auth may return without any further interaction.
selectAccount
(optional)
booleanWhen true, the service will allow the user to switch between accounts (if possible).

Default: false.
shouldAutoExchangeCode
(optional)
booleanShould the hook automatically exchange the response code for an authentication token.Defaults to true on installed apps (iOS, Android) when ResponseType.Code is used (default).
webClientId
(optional)
stringExpo web client ID for use in the browser.This Google Client ID must be setup as follows:

Extends: TokenRequestConfig

Config used to request a token refresh, or code exchange.

NameTypeDescription
refreshToken
(optional)
stringThe refresh token issued to the client.

Extends: Partial<TokenRequestConfig>

Config used to revoke a token.

NameTypeDescription
tokenstringThe token that the client wants to get revoked.Section 3.1
tokenTypeHint
(optional)
TokenTypeHintA hint about the type of the token submitted for revocation.Section 3.2

Object returned from the server after a token response.

NameTypeDescription
access_tokenstring-
expires_in
(optional)
number-
id_token
(optional)
string-
issued_at
(optional)
number-
refresh_token
(optional)
string-
scope
(optional)
string-
token_type
(optional)
TokenType-

Config used to request a token refresh, revocation, or code exchange.

NameTypeDescription
clientIdstringA unique string representing the registration information provided by the client. The client identifier is not a secret; it is exposed to the resource owner and shouldn't be used alone for client authentication.The client identifier is unique to the authorization server. Section 2.2
clientSecret
(optional)
stringClient secret supplied by an auth provider. There is no secure way to store this on the client.Section 2.3.1
extraParams
(optional)
Record<string, string>Extra query params that'll be added to the query string.
scopes
(optional)
string[]List of strings to request access to.Section 3.3

NameTypeDescription
accessTokenstringThe access token issued by the authorization server.Section 4.2.2
expiresIn
(optional)
numberThe lifetime in seconds of the access token.For example, the value 3600 denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server should provide the expiration time via other means or document the default value. Section 4.2.2
idToken
(optional)
stringID Token value associated with the authenticated session.TokenResponse
issuedAt
(optional)
numberTime in seconds when the token was received by the client.
refreshToken
(optional)
stringThe refresh token, which can be used to obtain new access tokens using the same authorization grant.Section 5.1
scope
(optional)
stringThe scope of the access token. Only required if it's different to the scope that was requested by the client.Section 3.3
state
(optional)
stringRequired if the "state" parameter was present in the client authorization request. The exact value received from the client.Section 4.2.2
tokenType
(optional)
TokenTypeThe type of the token issued. Value is case insensitive.Section 7.1

  • Plain - This should not be used. When used, the code verifier will be sent to the server as-is.

    CodeChallengeMethod.Plain"plain"

  • S256 - The default and recommended method for transforming the code verifier.
    • Convert the code verifier to ASCII.
    • Create a digest of the string using crypto method SHA256.
    • Convert the digest to Base64 and URL encode it.

    CodeChallengeMethod.S256"S256"

Grant type values used in dynamic client registration and auth requests.

  • AuthorizationCode - Used for exchanging an authorization code for one or more tokens.Section 4.1.3

    GrantType.AuthorizationCode"authorization_code"

  • ClientCredentials - Used for client credentials flow.Section 4.4.2

    GrantType.ClientCredentials"client_credentials"

  • Implicit - Used when obtaining an access token.Section 4.2

    GrantType.Implicit"implicit"

  • RefreshToken - Used when exchanging a refresh token for a new token.Section 6

    GrantType.RefreshToken"refresh_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).

  • 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.Consent"consent"

  • 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.Login"login"

  • 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.

    Prompt.None"none"

  • SelectAccount - Server should prompt the user to select an account. Can be used to switch accounts. If it can't obtain an account selection choice made by the user, it must return an error, typically account_selection_required.

    Prompt.SelectAccount"select_account"

The client informs the authorization server of the desired grant type by using the response type.

  • Code - For requesting an authorization code as described by Section 4.1.1.

    ResponseType.Code"code"

  • IdToken - A custom registered type for getting an id_token from Google OAuth.

    ResponseType.IdToken"id_token"

  • Token - For requesting an access token (implicit grant) as described by Section 4.2.1.

    ResponseType.Token"token"

A hint about the type of the token submitted for revocation. If not included then the server should attempt to deduce the token type.

  • AccessToken - Access token.Section 1.4

    TokenTypeHint.AccessToken"access_token"

  • RefreshToken - Refresh token.Section 1.5

    TokenTypeHint.RefreshToken"refresh_token"

AuthSession has built-in support for some popular providers to make usage as easy as possible. These allow you to skip repetitive things like defining endpoints and abstract common features like language.

import * as Google from 'expo-auth-session/providers/google';
  • See the guide for more info on usage: Google Authentication.
  • Provides an extra loginHint parameter. If the user's email address is known ahead of time, it can be supplied to be the default option.
  • Enforces minimum scopes to ['openid', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'] for optimal usage with services like Firebase and Auth0.
  • By default, the authorization code will be automatically exchanged for an access token. This can be overridden with shouldAutoExchangeCode.
  • Automatically uses the proxy in Expo Go because native auth is not supported due to custom build time configuration. This can be overridden with redirectUriOptions.useProxy.
  • Defaults to using the bundle ID and package name for the native URI redirect instead of the reverse client ID.
  • Disables PKCE for implicit and id-token based auth responses.
  • On web, the popup is presented with the dimensions that are optimized for the Google login UI ({ width: 515, height: 680 }).

A hook used for opinionated Google authentication that works across platforms.

  • config (GoogleAuthRequestConfig) - A GoogleAuthRequestConfig object with client IDs for each platform that should be supported.
  • redirectUriOptions (AuthSessionRedirectUriOptions) - Optional properties used to construct the redirect URI (passed to makeRedirectUriAsync()).

  • request (GoogleAuthRequest | null) - An instance of GoogleAuthRequest that can be used to prompt the user for authorization. This will be null until the auth request has finished loading.
  • response (AuthSessionResult | null) - This is null until promptAsync has been invoked. Once fulfilled it will return information about the authorization.
  • promptAsync (function) - When invoked, a web browser will open up and prompt the user for authentication. Accepts an AuthRequestPromptOptions object with options about how the prompt will execute. This should not be used to enable the Expo proxy service auth.expo.io, as the proxy will be automatically enabled based on the platform.

A DiscoveryDocument object containing the discovery URLs used for Google auth.

import * as Facebook from 'expo-auth-session/providers/facebook';
  • Uses implicit auth (ResponseType.Token) by default.
  • See the guide for more info on usage: Facebook Authentication.
  • Enforces minimum scopes to ['public_profile', 'email'] for optimal usage with services like Firebase and Auth0.
  • Uses display=popup for better UI results.
  • Automatically uses the proxy in Expo Go because native auth is not supported due to custom build time configuration.
  • The URI redirect must be added to your app.config.js or app.json as facebookScheme: 'fb<YOUR FBID>'.
  • Disables PKCE for implicit auth response.
  • On web, the popup is presented with the dimensions { width: 700, height: 600 }

A hook used for opinionated Facebook authentication that works across platforms.

  • config (FacebookAuthRequestConfig) - A FacebookAuthRequestConfig object with client IDs for each platform that should be supported.
  • redirectUriOptions (AuthSessionRedirectUriOptions) - Optional properties used to construct the redirect URI (passed to makeRedirectUriAsync()).

  • request (FacebookAuthRequest | null) - An instance of FacebookAuthRequest that can be used to prompt the user for authorization. This will be null until the auth request has finished loading.
  • response (AuthSessionResult | null) - This is null until promptAsync has been invoked. Once fulfilled it will return information about the authorization.
  • promptAsync (function) - When invoked, a web browser will open up and prompt the user for authentication. Accepts an AuthRequestPromptOptions object with options about how the prompt will execute.

A DiscoveryDocument object containing the discovery URLs used for Facebook auth.

In managed apps, AuthSession uses Expo servers to create a proxy between your application and the auth provider. If you'd like, you can also create your own proxy service.

This service is responsible for:
  • redirecting traffic from your application to the authentication service
  • redirecting response from the auth service to your application using a deep link
To better understand how it works, check out this implementation in Node.js:
const http = require('http');
const url = require('url');

const PORT = PORT;
const DEEP_LINK = DEEP_LINK_TO_YOUR_APPLICATION;

const redirect = (response, url) => {
  response.writeHead(302, {
    Location: url,
  });
  response.end();
}

http
  .createServer((request, response) => {
    // get parameters from request
    const parameters = url.parse(request.url, true).query;

    // if parameters contain authServiceUrl, this request comes from the application
    if (parameters.authServiceUrl) {
      // redirect user to the authUrl
      redirect(response, decodeURIComponent(parameters.authServiceUrl));
      return;
    }

    // redirect response from the auth service to your application
    redirect(response, DEEP_LINK);
  })
  .listen(PORT);
Client code which works with this service:
const authServiceUrl = encodeURIComponent(YOUR_AUTH_URL); // we encode this, because it will be send as a query parameter
const authServiceUrlParameter = `authServiceUrl=${authServiceUrl}`;
const authUrl = `YOUR_PROXY_SERVICE_URL?${authServiceUrlParameter}`;
const result = await AuthSession.startAsync({
  authUrl,
  returnUrl: YOUR_DEEP_LINK,
});

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 guide); 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.

If you are using deep linking with React Navigation v5, filtering through Linking.addEventListener will not be sufficient, because deep linking is handled differently. Instead, to filter these events you can add a custom getStateFromPath function to your linking configuration, and then filter by URL in the same way as described above.