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:
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 andreact-native-fbsdk-next
for Facebook. For more information, see Authentication overview.
expo-crypto
is a peer dependency and must be installed alongsideexpo-auth-session
.
-
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.
Use the uri-scheme
CLI to easily add, remove, list, and open your URIs.
To make your native app handle mycoolredirect://
simply run:
-
npx uri-scheme add mycoolredirect
You should now be able to see a list of all your project's schemes by running:
-
npx uri-scheme list
You can test it to ensure it works like this:
# 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
{
"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).
The guides have moved: Authentication Guide.
The typical flow for browser-based authentication in mobile apps is as follows:
import * as AuthSession from 'expo-auth-session';
Parameter | Type | Description |
---|---|---|
config | AuthRequestConfig | A valid |
discovery | null | DiscoveryDocument | A loaded |
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.
[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.Example
const [request, response, promptAsync] = useAuthRequest({ ... }, { ... });
Parameter | Type |
---|---|
request | null | AuthRequest |
discovery | null | DiscoveryDocument |
customOptions(optional) | AuthRequestPromptOptions |
[AuthSessionResult | null, PromptMethod]
Parameter | Type | Description |
---|---|---|
issuerOrDiscovery | IssuerOrDiscovery | URL using the |
Given an OpenID Connect issuer URL, this will fetch and return the DiscoveryDocument
(a collection of URLs) from the resource provider.
DiscoveryDocument | null
Returns null
until the DiscoveryDocument
has been fetched from the provided issuer URL.
Example
const discovery = useAutoDiscovery('https://example.com/auth');
Parameter | Type |
---|---|
config | AuthRequestConfig |
discovery | null | DiscoveryDocument |
AuthRequestInstance | AuthRequest |
AuthRequest | null
Type: Class extends TokenRequest<AccessTokenRequestConfig>
implements AccessTokenRequestConfig
Access token request. Exchange an authorization code for a user access token.
AccessTokenRequest Properties
GrantType
AccessTokenRequest Methods
Headers
{
clientId: string,
clientSecret: undefined | string,
code: string,
extraParams: undefined | Record<string, string>,
grantType: GrantType,
redirectUri: string,
scopes: undefined | string[]
}
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
string
Used 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:
parseReturnUrlAsync()
.makeAuthUrlAsync()
.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>
Parameter | Type |
---|---|
discovery | AuthDiscoveryDocument |
promptOptions(optional) | AuthRequestPromptOptions |
Prompt a user to authorize for a code.
Promise<AuthSessionResult>
Type: Class extends TokenRequest<RefreshTokenRequestConfig>
implements RefreshTokenRequestConfig
Refresh request.
RefreshTokenRequest Properties
GrantType
RefreshTokenRequest Methods
Headers
{
clientId: string,
clientSecret: undefined | string,
extraParams: undefined | Record<string, string>,
grantType: GrantType,
refreshToken: undefined | string,
scopes: undefined | string[]
}
Request Methods
Type: Class extends CodedError
ResponseError Properties
string
Used 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: undefined | string,
clientSecret: undefined | string,
token: string,
tokenTypeHint: undefined | TokenTypeHint
}
Parameter | Type | Description |
---|---|---|
discovery | Pick<DiscoveryDocument, 'revocationEndpoint'> | The |
Perform a token revocation request.
Promise<boolean>
Type: Class extends ResponseError
TokenError Properties
string
Used to assist the client developer in understanding the error that occurred.
Type: Class extends Request<T, TokenResponse>
A generic token request.
TokenRequest Properties
GrantType
TokenRequest Methods
Headers
Type: Class implements TokenResponseConfig
Token Response.
TokenResponse Methods
Parameter | Type |
---|---|
params | Record<string, any> |
Creates a TokenResponse
from query parameters returned from an AuthRequest
.
TokenResponse
TokenResponseConfig
Parameter | Type |
---|---|
token | Pick<TokenResponse, 'expiresIn' | 'issuedAt'> |
secondsMargin(optional) | number |
Determines whether a token refresh request must be made to refresh the tokens
boolean
Parameter | Type |
---|---|
config | Omit<TokenRequestConfig, 'refreshToken' | 'grantType'> |
discovery | Pick<DiscoveryDocument, 'tokenEndpoint'> |
Promise<TokenResponse>
Parameter | Type | Description |
---|---|---|
config | AccessTokenRequestConfig | Configuration used to exchange the code for a token. |
discovery | Pick<DiscoveryDocument, 'tokenEndpoint'> | The |
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.
Parameter | Type | Description |
---|---|---|
issuer | string | An |
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.
Parameter | Type | Description |
---|---|---|
config | Pick<TokenResponse, 'accessToken'> | The |
discovery | Pick<DiscoveryDocument, 'userInfoEndpoint'> | The |
Returns the current time in seconds.
number
Parameter | Type |
---|---|
urlPath(optional) | string |
options(optional) | Omit<CreateURLOptions, 'queryParams'> |
string
Deprecated Use
makeRedirectUri()
instead.
Parameter | Type |
---|---|
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.
string
Example
const url = AuthSession.getRedirectUrl('redirect');
// Managed: https://auth.expo.io/@your-username/your-app-slug/redirect
// Web: https://localhost:19006/redirect
Parameter | Type |
---|---|
issuer | string |
Append the well known resources path and OpenID connect discovery document path to a URL https://tools.ietf.org/html/rfc5785
string
Parameter | Type | Description |
---|---|---|
config | AuthRequestConfig | A valid |
issuerOrDiscovery | IssuerOrDiscovery | A loaded |
Build an AuthRequest
and load it before returning.
Promise<AuthRequest>
Returns an instance of AuthRequest
that can be used to prompt the user for authorization.
Parameter | Type | Description |
---|---|---|
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.
window.location
. For production web apps, you should hard code the URL as well.scheme
property of your app config.native
option for bare workflow React Native apps.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
Parameter | Type | Description |
---|---|---|
config | RefreshTokenRequestConfig | Configuration used to refresh the given access token. |
discovery | Pick<DiscoveryDocument, 'tokenEndpoint'> | The |
Refresh an access token.
refresh_token
then the access token may not be refreshed.expires_in
then it's assumed that the token does not expire.TokenResponse.isTokenFresh()
or shouldRefresh()
on an instance of TokenResponse
.Promise<TokenResponse>
Returns a discovery document with a valid tokenEndpoint
URL.
See: Section 6.
Parameter | Type |
---|---|
issuerOrDiscovery | IssuerOrDiscovery |
Utility method for resolving the discovery document from an issuer or object.
Promise<DiscoveryDocument>
Parameter | Type | Description |
---|---|---|
config | RevokeTokenRequestConfig | Configuration used to revoke a refresh or access token. |
discovery | Pick<DiscoveryDocument, 'revocationEndpoint'> | The |
Revoke a token with a provider. This makes the token unusable, effectively requiring the user to login again.
Promise<boolean>
Returns a discovery document with a valid revocationEndpoint
URL. Many providers do not support this feature.
Config used to exchange an authorization code for an access token.
See: Section 4.1.3
Type: TokenRequestConfig
extended by:
Property | Type | Description |
---|---|---|
code | string | The authorization code received from the authorization server. |
redirectUri | string | If the |
Type: Pick<DiscoveryDocument, 'authorizationEndpoint'>
Type: ResponseErrorConfig
extended by:
Property | Type | Description |
---|---|---|
state(optional) | string | Required only if state is used in the initial request |
Represents an OAuth authorization request as JSON.
Property | Type | Description |
---|---|---|
clientId | string | 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. |
clientSecret(optional) | string | Client secret supplied by an auth provider. There is no secure way to store this on the client. |
codeChallenge(optional) | string | Derived from the code verifier by using the |
codeChallengeMethod(optional) | CodeChallengeMethod | Method used to generate the code challenge. You should never use 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. |
redirectUri | string | After completing an interaction with a resource owner the server will redirect to this URI. Learn more about linking in Expo. |
responseType(optional) | ResponseType | string | |
scopes(optional) | string[] | List of strings to request access to. |
state(optional) | string | Used for protection against Cross-Site Request Forgery. |
usePKCE(optional) | boolean | Should use Proof Key for Code Exchange. Default: true |
Options passed to the promptAsync()
method of AuthRequest
s.
This can be used to configure how the web browser should look and behave.
Type: Omit<WebBrowserOpenOptions, 'windowFeatures'>
extended by:
Property | Type | Description |
---|---|---|
url(optional) | string | URL to open when prompting the user. This usually should be defined internally and left |
windowFeatures(optional) | WebBrowserWindowFeatures | Only for: Web Features to use with |
Options passed to makeRedirectUri
.
Property | Type | Description |
---|---|---|
isTripleSlashed(optional) | boolean | Should the URI be triple slashed |
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 |
path(optional) | string | Optional path to append to a URI. This will not be added to |
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(optional) | string | URI protocol |
Object returned after an auth request has completed.
{ type: 'cancel' }
.AuthSession.dismiss()
, the result is { type: 'dismiss' }
.{ type: 'success', params: Object, event: Object }
.{ type: 'error', params: Object, error: string, event: Object }
.Type: object
shaped as below:
Property | Type | Description |
---|---|---|
type | 'cancel' | 'dismiss' | 'opened' | 'locked' | How the auth completed. |
Or object shaped as below:
Property | Type | Description |
---|---|---|
authentication | TokenResponse | null | Returned when the auth finishes with an |
error(optional) | AuthError | null | Possible error if the auth failed with type |
errorCode | string | null |
|
params | Record<string, string> | Query params from the |
type | 'error' | 'success' | How the auth completed. |
url | string | Auth URL that was opened |
Property | Type | Description |
---|---|---|
authorizationEndpoint(optional) | string | Used to interact with the resource owner and obtain an authorization grant. |
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. |
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. |
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). |
userInfoEndpoint(optional) | string | URL of the OP's UserInfo Endpoint used to return info about the authenticated user. |