Expo AuthSession

GitHub

npm

A universal library that provides an API to handle browser-based authentication.

Android
iOS
Web

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: AuthSession enables 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-signin for Google authentication and react-native-fbsdk-next for Facebook. For more information, see Authentication overview.

Installation

expo-crypto is a peer dependency and must be installed alongside expo-auth-session.

Terminal
npx expo install expo-auth-session expo-crypto

If you are installing this in an existing React Native app, start by installing expo in your project. Then, follow the additional instructions as mentioned by the library's README under "Installation in bare React Native projects" section.

Are you using this library in a bare React Native app?

Use the uri-scheme CLI 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 emulator
yarn android
yarn ios

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

Usage in standalone apps

app.json
{
  "expo": {
    "scheme": "mycoolredirect"
  }
}

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

useAuthRequest(config, discovery)

Android
iOS
Web
ParameterTypeDescription
configAuthRequestConfig

A valid AuthRequestConfig that specifies what provider to use.

discoverynull | DiscoveryDocument

A loaded DiscoveryDocument with endpoints used for authenticating. Only authorizationEndpoint is required for requesting an authorization code.


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.

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.

Example

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

useAuthRequestResult(request, discovery, customOptions)

Android
iOS
Web
ParameterType
requestnull | AuthRequest
discoverynull | DiscoveryDocument
customOptions(optional)AuthRequestPromptOptions

useAutoDiscovery(issuerOrDiscovery)

Android
iOS
Web
ParameterTypeDescription
issuerOrDiscoveryIssuerOrDiscovery

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.

Returns:
DiscoveryDocument | null

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

Example

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

useLoadedAuthRequest(config, discovery, AuthRequestInstance)

Android
iOS
Web
ParameterType
configAuthRequestConfig
discoverynull | DiscoveryDocument
AuthRequestInstanceAuthRequest

Returns:
AuthRequest | null

Classes

AccessTokenRequest

Android
iOS
Web

Type: Class extends TokenRequest<AccessTokenRequestConfig> implements AccessTokenRequestConfig

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

Section 4.1.3

AccessTokenRequest Properties

grantType

Android
iOS
Web
Type: GrantType

AccessTokenRequest Methods

getHeaders()

Android
iOS
Web
Returns:
Headers

getQueryBody()

Android
iOS
Web
Returns:
Record<string, string>

getRequestConfig()

Android
iOS
Web
Returns:
{ clientId: string, clientSecret: undefined | string, code: string, extraParams: undefined | Record<string, string>, grantType: GrantType, redirectUri: string, scopes: undefined | string[] }

performAsync(discovery)

Android
iOS
Web
ParameterType
discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

AuthError

Android
iOS
Web

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

code

Android
iOS
Web
Type: string

description

Android
iOS
Web
Optional • Type: string

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

info

Android
iOS
Web
Optional • Type: any

params

Android
iOS
Web
Type: Record<string, string>

Raw results of the error.

state

Android
iOS
Web
Optional • Type: string

Required only if state is used in the initial request

uri

Android
iOS
Web
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.

AuthRequest

Android
iOS
Web

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

codeVerifier

Android
iOS
Web
Optional • Type: string

state

Android
iOS
Web
Type: string

Used for protection against Cross-Site Request Forgery.

url

Android
iOS
Web
Type: null | string • Default: null

AuthRequest Methods

getAuthRequestConfigAsync()

Android
iOS
Web

Load and return a valid auth request based on the input config.

makeAuthUrlAsync(discovery)

Android
iOS
Web
ParameterType
discoveryAuthDiscoveryDocument

Create the URL for authorization.

Returns:
Promise<string>

parseReturnUrl(url)

Android
iOS
Web
ParameterType
urlstring

promptAsync(discovery, promptOptions)

Android
iOS
Web
ParameterType
discoveryAuthDiscoveryDocument
promptOptions(optional)AuthRequestPromptOptions

Prompt a user to authorize for a code.

RefreshTokenRequest

Android
iOS
Web

Type: Class extends TokenRequest<RefreshTokenRequestConfig> implements RefreshTokenRequestConfig

Refresh request.

Section 6

RefreshTokenRequest Properties

grantType

Android
iOS
Web
Type: GrantType

RefreshTokenRequest Methods

getHeaders()

Android
iOS
Web
Returns:
Headers

getQueryBody()

Android
iOS
Web
Returns:
Record<string, string>

getRequestConfig()

Android
iOS
Web
Returns:
{ clientId: string, clientSecret: undefined | string, extraParams: undefined | Record<string, string>, grantType: GrantType, refreshToken: undefined | string, scopes: undefined | string[] }

performAsync(discovery)

Android
iOS
Web
ParameterType
discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

Request

Android
iOS
Web

Request Methods

getQueryBody()

Android
iOS
Web
Returns:
Record<string, string>

getRequestConfig()

Android
iOS
Web
Returns:
T

performAsync(discovery)

Android
iOS
Web
ParameterType
discoveryDiscoveryDocument

Returns:
Promise<B>

ResponseError

Android
iOS
Web

Type: Class extends CodedError

ResponseError Properties

code

Android
iOS
Web
Type: string

description

Android
iOS
Web
Optional • Type: string

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

info

Android
iOS
Web
Optional • Type: any

params

Android
iOS
Web
Type: Record<string, string>

Raw results of the error.

uri

Android
iOS
Web
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.

RevokeTokenRequest

Android
iOS
Web

Type: Class extends Request<RevokeTokenRequestConfig, boolean> implements RevokeTokenRequestConfig

Revocation request for a given token.

Section 2.1

RevokeTokenRequest Methods

getHeaders()

Android
iOS
Web
Returns:
Headers

getQueryBody()

Android
iOS
Web
Returns:
Record<string, string>

getRequestConfig()

Android
iOS
Web
Returns:
{ clientId: undefined | string, clientSecret: undefined | string, token: string, tokenTypeHint: undefined | TokenTypeHint }

performAsync(discovery)

Android
iOS
Web
ParameterTypeDescription
discoveryPick<DiscoveryDocument, 'revocationEndpoint'>

The revocationEndpoint for a provider.


Perform a token revocation request.

Returns:
Promise<boolean>

TokenError

Android
iOS
Web

Type: Class extends ResponseError

TokenError Properties

code

Android
iOS
Web
Type: string

description

Android
iOS
Web
Optional • Type: string

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

info

Android
iOS
Web
Optional • Type: any

params

Android
iOS
Web
Type: Record<string, string>

Raw results of the error.

uri

Android
iOS
Web
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.

TokenRequest

Android
iOS
Web

Type: Class extends Request<T, TokenResponse>

A generic token request.

TokenRequest Properties

clientId

Android
iOS
Web
Read Only • Type: string

clientSecret

Android
iOS
Web
Optional • Read Only • Type: string

extraParams

Android
iOS
Web
Optional • Read Only • Type: Record<string, string>

grantType

Android
iOS
Web
Type: GrantType

scopes

Android
iOS
Web
Optional • Read Only • Type: string[]

TokenRequest Methods

getHeaders()

Android
iOS
Web
Returns:
Headers

getQueryBody()

Android
iOS
Web
Returns:
Record<string, string>

getRequestConfig()

Android
iOS
Web
Returns:
T

performAsync(discovery)

Android
iOS
Web
ParameterType
discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

TokenResponse

Android
iOS
Web

Type: Class implements TokenResponseConfig

Token Response.

Section 5.1

TokenResponse Methods

fromQueryParams(params)

Android
iOS
Web
ParameterType
paramsRecord<string, any>

Creates a TokenResponse from query parameters returned from an AuthRequest.

getRequestConfig()

Android
iOS
Web

isTokenFresh(token, secondsMargin)

Android
iOS
Web
ParameterType
tokenPick<TokenResponse, 'expiresIn' | 'issuedAt'>
secondsMargin(optional)number

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

Returns:
boolean

refreshAsync(config, discovery)

Android
iOS
Web
ParameterType
configOmit<TokenRequestConfig, 'refreshToken' | 'grantType'>
discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

shouldRefresh()

Android
iOS
Web
Returns:
boolean

Methods

AuthSession.dismiss()

Android
iOS
Web

Cancels an active AuthSession if there is one.

Returns:
void

AuthSession.exchangeCodeAsync(config, discovery)

Android
iOS
Web
ParameterTypeDescription
configAccessTokenRequestConfig

Configuration used to exchange the code for a token.

discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

The tokenEndpoint for a provider.


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.

AuthSession.fetchDiscoveryAsync(issuer)

Android
iOS
Web
ParameterTypeDescription
issuerstring

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.

AuthSession.fetchUserInfoAsync(config, discovery)

Android
iOS
Web
ParameterTypeDescription
configPick<TokenResponse, 'accessToken'>

The accessToken for a user, returned from a code exchange or auth request.

discoveryPick<DiscoveryDocument, 'userInfoEndpoint'>

The userInfoEndpoint for a provider.


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

Returns:
Promise<Record<string, any>>

See: UserInfo.

AuthSession.getCurrentTimeInSeconds()

Android
iOS
Web

Returns the current time in seconds.

Returns:
number

AuthSession.getDefaultReturnUrl(urlPath, options)

Android
iOS
Web
ParameterType
urlPath(optional)string
options(optional)Omit<CreateURLOptions, 'queryParams'>

Returns:
string

Deprecated Use makeRedirectUri() instead.

AuthSession.getRedirectUrl(path)

Android
iOS
Web
ParameterType
path(optional)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.

Returns:
string

Example

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

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

AuthSession.issuerWithWellKnownUrl(issuer)

Android
iOS
Web
ParameterType
issuerstring

Append the well known resources path and OpenID connect discovery document path to a URL https://tools.ietf.org/html/rfc5785

Returns:
string

AuthSession.loadAsync(config, issuerOrDiscovery)

Android
iOS
Web
ParameterTypeDescription
configAuthRequestConfig

A valid AuthRequestConfig that specifies what provider to use.

issuerOrDiscoveryIssuerOrDiscovery

A loaded DiscoveryDocument or issuer URL. (Only authorizationEndpoint is required for requesting an authorization code).


Build an AuthRequest and load it before returning.

Returns an instance of AuthRequest that can be used to prompt the user for authorization.

AuthSession.makeRedirectUri(options)

Android
iOS
Web
ParameterTypeDescription
options(optional)AuthSessionRedirectUriOptions

Additional options for configuring the path.

Default:{}

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.
  • Bare workflow: Will fallback to using the native option for bare workflow React Native apps.
Returns:
string

The 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

AuthSession.refreshAsync(config, discovery)

Android
iOS
Web
ParameterTypeDescription
configRefreshTokenRequestConfig

Configuration used to refresh the given access token.

discoveryPick<DiscoveryDocument, 'tokenEndpoint'>

The tokenEndpoint for a provider.


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.

Returns a discovery document with a valid tokenEndpoint URL.

See: Section 6.

AuthSession.requestAsync(requestUrl, fetchRequest)

Android
iOS
Web
ParameterType
requestUrlstring
fetchRequestFetchRequest

Returns:
Promise<T>

AuthSession.resolveDiscoveryAsync(issuerOrDiscovery)

Android
iOS
Web
ParameterType
issuerOrDiscoveryIssuerOrDiscovery

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

AuthSession.revokeAsync(config, discovery)

Android
iOS
Web
ParameterTypeDescription
configRevokeTokenRequestConfig

Configuration used to revoke a refresh or access token.

discoveryPick<DiscoveryDocument, 'revocationEndpoint'>

The revocationEndpoint for a provider.


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

Returns:
Promise<boolean>

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

Types

AccessTokenRequestConfig

Android
iOS
Web

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

Type: TokenRequestConfig extended by:

PropertyTypeDescription
codestring

The authorization code received from the authorization server.

redirectUristring

If the redirectUri parameter was included in the AuthRequest, then it must be supplied here as well.

Section 3.1.2

AuthDiscoveryDocument

Android
iOS
Web

Type: Pick<DiscoveryDocument, 'authorizationEndpoint'>

AuthErrorConfig

Android
iOS
Web

Type: ResponseErrorConfig extended by:

PropertyTypeDescription
state(optional)string

Required only if state is used in the initial request

AuthRequestConfig

Android
iOS
Web

Represents an OAuth authorization request as JSON.

PropertyTypeDescription
clientIdstring

A 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)string

Client secret supplied by an auth provider. There is no secure way to store this on the client.

Section 2.3.1

codeChallenge(optional)string

Derived from the code verifier by using the CodeChallengeMethod.

Section 4.2

codeChallengeMethod(optional)CodeChallengeMethod

Method 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)Prompt | Prompt[]

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.

Section 3.1.2.1

redirectUristring

After 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)ResponseType | string

Specifies 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)string

Used for protection against Cross-Site Request Forgery.

usePKCE(optional)boolean

Should use Proof Key for Code Exchange.

Default:true

AuthRequestPromptOptions

Android
iOS
Web

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

Type: Omit<WebBrowserOpenOptions, 'windowFeatures'> extended by:

PropertyTypeDescription
url(optional)string

URL to open when prompting the user. This usually should be defined internally and left undefined in most cases.

windowFeatures(optional)WebBrowserWindowFeatures
Only for:
Web

Features to use with window.open().

AuthSessionRedirectUriOptions

Android
iOS
Web

Options passed to makeRedirectUri.

PropertyTypeDescription
isTripleSlashed(optional)boolean

Should the URI be triple slashed scheme:///path or double slashed scheme://path. Defaults to false.

native(optional)string

Manual 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)string

Optional path to append to a URI. This will not be added to native.

preferLocalhost(optional)boolean

Attempt 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
queryParams(optional)Record<string, string | undefined>

Optional native scheme URI protocol <scheme>:// that must be built into your native app.

scheme(optional)string

URI protocol <scheme>:// that must be built into your native app.

AuthSessionResult

Android
iOS
Web

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:

PropertyTypeDescription
type'cancel' | 'dismiss' | 'opened' | 'locked'

How the auth completed.

Or object shaped as below:

PropertyTypeDescription
authenticationTokenResponse | null

Returned when the auth finishes with an access_token property.

error(optional)AuthError | null

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

urlstring

Auth URL that was opened

DiscoveryDocument

Android
iOS
Web
PropertyTypeDescription
authorizationEndpoint(optional)string

Used to interact with the resource owner and obtain an authorization grant.

Section 3.1

discoveryDocument(optional)ProviderMetadata

All metadata about the provider.

endSessionEndpoint(optional)string

URL 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)string

URL of the OP's Dynamic Client Registration Endpoint.

revocationEndpoint(optional)string

Used 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)string

Used 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)string

URL of the OP's UserInfo Endpoint used to return info about the authenticated user.

UserInfo