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是一个同级依赖,必须与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 的列表:
你可以这样测试它是否正常工作:
独立应用中的使用
为了能够通过深度链接回到你的应用,你需要在项目的应用配置中设置一个 scheme,然后构建你的独立应用(它不能通过更新来修改)。如果你不包含 scheme,身份验证流程将会完成,但它无法将信息传回你的应用,用户将不得不手动退出身份验证模态框(这将导致一个取消事件)。
指南
指南已迁移:Authentication Guide。
基于网页浏览器的身份验证流程如何工作
移动应用中基于浏览器的身份验证典型流程如下:
- 开始:用户点击登录按钮
- 打开网页浏览器:应用会打开一个网页浏览器,跳转到身份验证提供商的登录页面。打开登录页面的 URL 通常包含用于标识应用的信息,以及成功后要重定向到的 URL。注意:网页浏览器应与你的系统网页浏览器共享 cookie,这样如果用户已经在系统浏览器中完成身份验证,就无需再次登录——Expo 的 WebBrowser API 会处理这一点。
- 身份验证提供商重定向:身份验证成功后,如果重定向 URL 在允许的重定向 URL 白名单中,身份验证提供商应通过重定向到登录页面查询参数中由应用提供的 URL,将用户重定向回应用程序(了解更多移动应用中的链接工作方式)。将重定向 URL 加入白名单很重要,这可以防止恶意行为者伪装成你的应用。重定向会在 URL 中包含数据(例如用户 id 和 token),这些数据可能位于 location hash、查询参数,或两者中。
- 应用处理重定向:应用接收到重定向后,会对重定向 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: string | undefined,
code: string,
extraHeaders: Record<string, string> | undefined,
extraParams: Record<string, string> | undefined,
grantType: GrantType,
redirectUri: string,
scopes: string[] | undefined
}Type: Class extends ResponseError
Represents an authorization response error: Section 5.2. Often times providers will fail to return the proper error message for a given error code. This error method will add the missing description for more context on what went wrong.
AuthError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class implements Omit<AuthRequestConfig, 'state'>
Used to manage an authorization request according to the OAuth spec: Section 4.1.1. You can use this class directly for more info around the authorization.
Common use-cases:
- Parse a URL returned from the authorization server with
parseReturnUrlAsync(). - Get the built authorization URL with
makeAuthUrlAsync(). - Get a loaded JSON representation of the auth request with crypto state loaded with
getAuthRequestConfigAsync().
Example
// Create a request. const request = new AuthRequest({ ... }); // Prompt for an auth code const result = await request.promptAsync(discovery); // Get the URL to invoke const url = await request.makeAuthUrlAsync(discovery); // Get the URL to invoke const parsed = await request.parseReturnUrlAsync("<URL From Server>");
AuthRequest Properties
AuthRequest Methods
Load and return a valid auth request based on the input config.
Promise<AuthRequestConfig>Type: Class extends TokenRequest<RefreshTokenRequestConfig> implements RefreshTokenRequestConfig
Refresh request.
RefreshTokenRequest Properties
GrantTypeRefreshTokenRequest Methods
Headers{
clientId: string,
clientSecret: string | undefined,
extraHeaders: Record<string, string> | undefined,
extraParams: Record<string, string> | undefined,
grantType: GrantType,
refreshToken: string | undefined,
scopes: string[] | undefined
}Request Methods
Type: Class extends CodedError
ResponseError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class extends Request<RevokeTokenRequestConfig, boolean> implements RevokeTokenRequestConfig
Revocation request for a given token.
RevokeTokenRequest Methods
Headers{
clientId: string | undefined,
clientSecret: string | undefined,
extraHeaders: Record<string, string> | undefined,
token: string,
tokenTypeHint: TokenTypeHint | undefined
}Type: Class extends ResponseError
TokenError Properties
stringUsed to assist the client developer in understanding the error that occurred.
Type: Class extends Request<T, TokenResponse> implements TokenRequestConfig
A generic token request.
TokenRequest Properties
GrantTypeTokenRequest Methods
HeadersType: Class implements TokenResponseConfig
Token Response.
TokenResponse Properties
TokenResponse Methods
TokenResponseConfigDetermines whether a token refresh request must be made to refresh the tokens
booleanMethods
Exchange an authorization code for an access token that can be used to get data from the provider.
Promise<TokenResponse>Returns a discovery document with a valid tokenEndpoint URL.
Fetch a DiscoveryDocument from a well-known resource provider that supports auto discovery.
Promise<DiscoveryDocument>Returns a discovery document that can be used for authentication.
Returns the current time in seconds.
numberDeprecated: Use
makeRedirectUri()instead.
Get the URL that your authentication provider needs to redirect to. For example: https://auth.expo.io/@your-username/your-app-slug. You can pass an additional path component to be appended to the default redirect URL.
Note This method will throw an exception if you're using the bare workflow on native.
stringExample
const url = AuthSession.getRedirectUrl('redirect'); // Managed: https://auth.expo.io/@your-username/your-app-slug/redirect // Web: https://localhost:19006/redirect
Append the well known resources path and OpenID connect discovery document path to a URL https://tools.ietf.org/html/rfc5785
stringBuild an AuthRequest and load it before returning.
Promise<AuthRequest>Returns an instance of AuthRequest that can be used to prompt the user for authorization.
Create a redirect url for the current platform and environment. You need to manually define the redirect that will be used in a bare workflow React Native app, or an Expo standalone app, this is because it cannot be inferred automatically.
- Web: Generates a path based on the current
window.location. For production web apps, you should hard code the URL as well. - Managed workflow: Uses the
schemeproperty of your app config. - Bare workflow: Will fallback to using the
nativeoption for bare workflow React Native apps.
stringThe redirectUri to use in an authentication request.
Example
const redirectUri = makeRedirectUri({ scheme: 'my-scheme', path: 'redirect' }); // Development Build: my-scheme://redirect // Expo Go: exp://127.0.0.1:8081/--/redirect // Web dev: https://localhost:19006/redirect // Web prod: https://yourwebsite.com/redirect const redirectUri2 = makeRedirectUri({ scheme: 'scheme2', preferLocalhost: true, isTripleSlashed: true, }); // Development Build: scheme2:/// // Expo Go: exp://localhost:8081 // Web dev: https://localhost:19006 // Web prod: https://yourwebsite.com
Refresh an access token.
- If the provider didn't return a
refresh_tokenthen the access token may not be refreshed. - If the provider didn't return a
expires_inthen it's assumed that the token does not expire. - Determine if a token needs to be refreshed via
TokenResponse.isTokenFresh()orshouldRefresh()on an instance ofTokenResponse.
Promise<TokenResponse>Returns a discovery document with a valid tokenEndpoint URL.
See: Section 6.
Utility method for resolving the discovery document from an issuer or object.
Promise<DiscoveryDocument>Revoke a token with a provider. This makes the token unusable, effectively requiring the user to login again.
Promise<boolean>Resolves to true when the revocation request completes. Rejects with an error if the provider does not expose a revocationEndpoint or the request fails. Many providers do not support this feature.
Types
Config used to exchange an authorization code for an access token.
See: Section 4.1.3
Type: TokenRequestConfig extended by:
Type: Pick<DiscoveryDocument, 'authorizationEndpoint'>
Options passed to the promptAsync() method of AuthRequests.
This can be used to configure how the web browser should look and behave.
Type: Omit<AuthSessionOpenOptions, 'windowFeatures'> extended by:
Object returned after an auth request has completed.
- If the user cancelled the authentication session by closing the browser, the result is
{ type: 'cancel' }. - If the authentication is dismissed manually with
AuthSession.dismiss(), the result is{ type: 'dismiss' }. - If the authentication flow is successful, the result is
{ type: 'success', params: Object, event: Object }. - If the authentication flow is returns an error, the result is
{ type: 'error', params: Object, error: string, event: Object }.
Type: object shaped as below:
Or object shaped as below:
URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier.
Type: string
OpenID Providers have metadata describing their configuration. ProviderMetadata
Type: Record<string, string | boolean | string[]> ProviderMetadataEndpoints extended by:
Config used to request a token refresh, or code exchange.
See: Section 6
Type: TokenRequestConfig extended by:
Config used to request a token refresh, revocation, or code exchange.
Enums
CodeChallengeMethod.Plain = "plain"This should not be used. When used, the code verifier will be sent to the server as-is.
Grant type values used in dynamic client registration and auth requests.
See: Appendix A.10
GrantType.AuthorizationCode = "authorization_code"Used for exchanging an authorization code for one or more tokens.
GrantType.ClientCredentials = "client_credentials"Used for client credentials flow.
GrantType.RefreshToken = "refresh_token"Used when exchanging a refresh token for a new token.
Informs the server if the user should be prompted to login or consent again. This can be used to present a dialog for switching accounts after the user has already been logged in. You should use this in favor of clearing cookies (which is mostly not possible on iOS).
See: Section 3.1.2.1.
Prompt.Consent = "consent"Server should prompt the user for consent before returning information to the client.
If it cannot obtain consent, it must return an error, typically consent_required.
Prompt.Login = "login"The server should prompt the user to reauthenticate.
If it cannot reauthenticate the End-User, it must return an error, typically login_required.
Prompt.None = "none"Server must not display any auth or consent UI. Can be used to check for existing auth or consent.
An error is returned if a user isn't already authenticated or the client doesn't have pre-configured consent for the requested claims, or does not fulfill other conditions for processing the request.
The error code will typically be login_required, interaction_required, or another code defined in Section 3.1.2.6.
The client informs the authorization server of the desired grant type by using the response type.
See: Section 3.1.1.
ResponseType.IdToken = "id_token"A custom registered type for getting an id_token from Google OAuth.
ResponseType.Token = "token"For requesting an access token (implicit grant) as described by Section 4.2.1.
A hint about the type of the token submitted for revocation. If not included then the server should attempt to deduce the token type.
See: Section 2.1
高级用法
在 Linking 处理器中过滤掉 AuthSession 事件
你可能希望处理进入应用的链接,原因有很多,比如推送通知,或者普通的深度链接(你可以在 Linking 中阅读更多相关内容);身份验证重定向只是深度链接的一种,而 AuthSession 会为你处理这些特定链接。在你自己的 Linking.addEventListener 处理器中,你可以通过检查 URL 是否包含 +expo-auth-session 字符串来过滤掉由 AuthSession 处理的深度链接——如果包含,就可以忽略它。这之所以有效,是因为 AuthSession 会在默认的 returnUrl 中添加 +expo-auth-session;不过,如果你提供了自己的 returnUrl,你可能也需要考虑添加类似的标识符,以便你能从其他处理器中过滤出 AuthSession 事件。
与 React Navigation 配合使用
如果你使用 React Navigation 进行深度链接,那么通过 Linking.addEventListener 进行过滤就不够了,因为深度链接的处理方式不同(handled differently)。相反,为了过滤这些事件,请在你的 linking 配置中添加一个自定义的 getStateFromPath 函数,然后再按上面描述的相同方式按 URL 进行过滤。