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,认证流程将会完成,但它无法将信息传回到你的应用中,用户将不得不手动退出认证弹窗(这将导致一个取消事件)。
指南
指南已迁移:认证指南。
Web 浏览器基础身份验证流程如何工作
移动应用中基于浏览器的身份验证典型流程如下:
- 发起:用户按下登录按钮
- 打开网页浏览器:应用会打开网页浏览器,跳转到身份验证提供方的登录页面。为登录页面打开的 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 in an existing React Native project 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 an existing React Native project or a production build, 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. - CNG projects: Uses the
schemeproperty of your app config. - Existing React Native apps: Falls back to using the
nativeoption.
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 进行过滤是不够的,因为深度链接的处理方式不同。相反,要过滤这些事件,请在你的 linking 配置中添加一个自定义的 getStateFromPath 函数,然后像上面描述的那样按 URL 进行过滤。