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
一个通用库,提供用于处理基于浏览器的身份验证的 API。
AuthSession 通过利用 WebBrowser 和 Crypto,使你的应用能够基于网页浏览器进行身份验证(例如,基于浏览器的 OAuth 流程)。有关实现细节,请参考此文档;有关用法,请参阅 Authentication 指南。
注意:
AuthSession支持通用的 OAuth 和 OpenID Connect 基于浏览器的认证流程。在可用的情况下,我们建议使用身份提供商提供的库,因为它会处理该提供商特有的实现细节。例如,Google 认证请使用@react-native-google-signin/google-signin,Facebook 认证请使用react-native-fbsdk-next。更多信息请参阅 Authentication 概览。
安装
expo-crypto是一个 peer dependency,必须与expo-auth-session一起安装。
If you are installing this in an existing React Native app, make sure to install expo in your project.
配置
Are you using this library in an existing React Native app?
要使用此库,你需要在应用中通过设置 scheme 来配置深度链接。使用 uri-scheme CLI 工具可以轻松添加、删除、列出和打开你的 URI。
例如,要让你的原生应用处理 mycoolredirect://,运行:
现在你应该可以通过运行以下命令看到项目中所有 scheme 的列表:
你可以这样测试它是否正常工作:
在独立应用中的用法
为了能够通过深度链接返回到你的应用,你需要在项目的 app 配置中设置一个 scheme,然后构建你的独立应用(它不能通过更新来修改)。如果你不包含 scheme,认证流程会完成,但它将无法把信息传回你的应用,用户将不得不手动退出认证弹窗(从而导致一个 canceled 事件)。
指南
指南已迁移:Authentication Guide。
基于网页浏览器的认证流程如何工作
移动应用中基于浏览器的认证流程通常如下:
- Initiation: 用户按下登录按钮
- Open web browser: 应用会打开一个网页浏览器,进入认证提供商的登录页面。打开登录页面的 url 通常包含用于标识应用的信息,以及成功后重定向到的 URL。注意:网页浏览器应当与系统网页浏览器共享 cookie,这样如果用户已经在系统浏览器中完成认证,就无需再次登录——Expo 的 WebBrowser API 会处理这一点。
- Authentication provider redirects: 认证成功后,认证提供商应通过重定向到应用在登录页面查询参数中提供的 URL,将用户重定向回应用(了解更多关于移动应用中链接如何工作),前提是该 URL 位于允许的重定向 URL 白名单中。将重定向 URL 加入白名单很重要,可以防止恶意行为者冒充你的应用。重定向会在 URL 中包含数据(例如用户 id 和 token),这些数据可能位于 location hash、查询参数,或两者中。
- App handles redirect: 应用处理该重定向,并从重定向 URL 中解析数据。
安全注意事项
- 切勿将任何密钥放入你的应用代码中,这没有任何安全方式! 相反,你应该把密钥存储在服务器上,并提供一个端点,由它为你的客户端发起 API 调用并将数据返回。
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: 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
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: undefined | string,
extraParams: undefined | Record<string, string>,
grantType: GrantType,
refreshToken: undefined | string,
scopes: undefined | string[]
}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: undefined | string,
clientSecret: undefined | string,
token: string,
tokenTypeHint: undefined | TokenTypeHint
}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
高级用法
在 Linking 处理器中过滤掉 AuthSession 事件
有许多原因会让你想要处理进入应用的链接,例如推送通知或普通的深度链接(你可以在 Linking 中阅读更多相关内容);认证重定向只是深度链接的一种,而 AuthSession 会为你处理这些特定链接。在你自己的 Linking.addEventListener 处理器中,你可以通过检查 URL 是否包含 +expo-auth-session 字符串来过滤掉由 AuthSession 处理的深度链接——如果包含,你可以忽略它。这之所以有效,是因为 AuthSession 会把 +expo-auth-session 添加到默认的 returnUrl 中;不过,如果你提供了自己的 returnUrl,你可能也要考虑添加类似的标识,以便从其他处理器中过滤出 AuthSession 事件。
与 React Navigation 配合使用
如果你在 React Navigation 中使用深度链接,仅通过 Linking.addEventListener 进行过滤是不够的,因为深度链接的处理方式不同。相反,要过滤这些事件,请在你的 linking 配置中添加自定义的 getStateFromPath 函数,然后像上面所述那样按 URL 进行过滤。