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。更多信息,请参见 认证 概览。
安装
🌐 Installation
expo-crypto是一个同级依赖,必须与expo-auth-session一起安装。
If you are installing this in an existing React Native app, make sure to install expo in your project.
配置
🌐 Configuration
Are you using this library in an existing React Native app?
要使用这个库,你需要在应用中通过设置 scheme 来配置深度链接。使用 uri-scheme 命令行接口 工具可以轻松添加、删除、列出和打开你的 URI。
🌐 To use this library, you need to set up deep linking in your app by setting up a scheme. Use the uri-scheme CLI utility to easily add, remove, list, and open your URIs.
例如,要让你的本地应用处理 mycoolredirect://,请运行:
🌐 For example, to make your native app handle mycoolredirect://, run:
你现在应该能够通过运行以下命令来查看所有项目方案的列表:
🌐 You should now be able to see a list of all your project's schemes by running:
你可以测试它以确保它像这样工作:
🌐 You can test it to ensure it works like this:
在独立应用中的使用
🌐 Usage in standalone apps
为了能够深度链接回你的应用,你需要在项目的应用配置中设置一个 scheme,然后构建你的独立应用(它无法通过更新来修改)。如果你没有包含一个 scheme,认证流程将会完成,但无法将信息传回你的应用,用户将需要手动退出认证弹窗(导致事件被取消)。
🌐 To be able to deep link back into your app, you will need to set a scheme in your project's app config, 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
指南已更新:认证指南。
基于 Web 浏览器的身份验证流程如何工作
🌐 How web browser based authentication flows work
移动应用中基于浏览器的身份验证的典型流程如下:
🌐 The typical flow for browser-based authentication in mobile apps is as follows:
- 启动:用户按下登录按钮
- 打开网页浏览器:该应用会打开一个网页浏览器,访问身份验证提供者的登录页面。用于登录页面的 URL 通常包含用于识别应用的信息,以及成功后重定向的 URL。注意:网页浏览器应与系统浏览器共享 Cookie,这样如果用户已在系统浏览器中完成身份验证,就无需再次登录 — Expo 的 WebBrowser API 会处理此问题。
- 身份验证提供者重定向:在身份验证成功后,身份验证提供者应通过重定向到登录页面查询参数中应用提供的 URL 来返回应用(了解有关移动应用中链接工作原理的更多信息),前提是该 URL 在允许的重定向 URL 白名单中。将重定向 URL 列入白名单对于防止恶意行为者冒充你的应用非常重要。重定向会在 URL 中包含数据(例如用户 ID 和令牌),可以放在位置哈希、查询参数或两者中。
- 应用处理重定向:重定向由应用处理,并从重定向 URL 中解析数据。
安全考虑
🌐 Security considerations
- 永远不要将任何密钥放在应用代码中,没有安全的方法可以这样做! 相反,你应该将密钥存储在服务器上,并提供一个端点,让它为你的客户端进行 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
高级用法
🌐 Advanced usage
过滤掉链接处理程序中的 AuthSession 事件
🌐 Filtering out AuthSession events in Linking handlers
有许多原因可能会让你希望处理进入你应用的入站链接,例如推送通知或普通的深度链接(你可以在 Linking 中了解更多);认证重定向只是深度链接的一种类型,而 AuthSession 为你处理这些特定的链接。在你自己的 Linking.addEventListener 处理器中,你可以通过检查 URL 是否包含 +expo-auth-session 字符串来过滤掉由 AuthSession 处理的深度链接——如果包含,你可以忽略它。这之所以可行,是因为 AuthSession 将 +expo-auth-session 添加到默认的 returnUrl;然而,如果你提供了自己的 returnUrl,你可能需要考虑添加类似的标识符,以便能够从其他处理器中过滤掉 AuthSession 事件。
🌐 There are many reasons why you might want to handle inbound links into your app, such as push notifications or just regular deep linking (you can read more about this in the Linking); authentication redirects are only one type of deep link, and AuthSession handles these particular links for you. In your own Linking.addEventListener handlers, you can filter out deep links that are handled by AuthSession by checking if the URL includes the +expo-auth-session string — if it does, you can ignore it. This works because AuthSession adds +expo-auth-session to the default returnUrl; however, if you provide your own returnUrl, you may want to consider adding a similar identifier to enable you to filter out AuthSession events from other handlers.
使用 React 导航
🌐 With React Navigation
如果你在使用 React Navigation 的深度链接,仅通过 Linking.addEventListener 进行过滤是不够的,因为深度链接是以不同方式处理的。相反,要过滤这些事件,请在你的链接配置中添加一个自定义的 getStateFromPath 函数,然后按上文所述的方式通过 URL 进行过滤。
🌐 If you are using deep linking with React Navigation, filtering through Linking.addEventListener will not be sufficient because deep linking is handled differently. Instead, to filter these events, add a custom getStateFromPath function to your linking configuration, and then filter by URL in the same way as described above.