一个通用库,提供 API 来处理基于浏览器的身份验证。
AuthSession
通过利用 WebBrowser 和 加密 在你的应用中启用基于 Web 浏览器的身份验证(例如,基于浏览器的 OAuth 流)。有关实现细节,请参阅此参考,有关使用方法,请参阅 验证 指南。
¥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.
¥Installation
expo-crypto
是对等依赖,必须与expo-auth-session
一起安装。¥
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 (bare workflow), start by installing expo
in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.
使用 uri-scheme
命令行接口 轻松添加、删除、列出和打开你的 URI。
¥Use the uri-scheme
CLI to easily add, remove, list, and open your URIs.
要使你的原生应用处理 mycoolredirect://
,只需运行:
¥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
¥Usage in standalone apps
{
"expo": {
"scheme": "mycoolredirect"
}
}
为了能够深层链接回你的应用,你需要在项目 app.config.js 或 app.json 中设置 scheme
,然后构建独立应用(无法通过更新进行更新)。如果你不包含方案,则身份验证流程将完成,但无法将信息传回你的应用,并且用户必须手动退出身份验证模式(导致事件取消)。
¥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).
¥Guides
指南已移动:认证指南。
¥The guides have moved: Authentication Guide.
¥How web browser based authentication flows work
移动应用中基于浏览器的身份验证的典型流程如下:
¥The typical flow for browser-based authentication in mobile apps is as follows:
引发:用户按下登录按钮
¥Initiation: the user presses a sign in button
打开网络浏览器:该应用会打开一个 Web 浏览器,访问身份验证提供商登录页面。为登录页面打开的 URL 通常包含用于标识应用的信息以及成功时重定向到的 URL。注意:Web 浏览器应与你的系统 Web 浏览器共享 Cookie,以便用户在已在系统浏览器上进行身份验证的情况下无需再次登录 - Expo 的 WebBrowser API 负责处理此问题。
¥Open web browser: the app opens up a web browser to the authentication provider sign in page. The url that is opened for the sign in page usually includes information to identify the app, and a URL to redirect to on success. Note: the web browser should share cookies with your system web browser so that users do not need to sign in again if they are already authenticated on the system browser -- Expo's WebBrowser API takes care of this.
身份验证提供商重定向:身份验证成功后,身份验证提供程序应通过重定向到应用在登录页面 (详细了解链接在移动应用中的工作原理) 上的查询参数中提供的 URL 来重定向回应用,前提是该 URL 位于允许的重定向 URL 的白名单中。将重定向 URL 列入白名单对于防止恶意行为者冒充你的应用非常重要。重定向包括 URL 中的数据(例如用户 ID 和令牌)、位置哈希、查询参数或两者。
¥Authentication provider redirects: upon successful authentication, the authentication provider should redirect back to the application by redirecting to URL provided by the app in the query parameters on the sign in page (read more about how linking works in mobile apps), provided that the URL is in the allowlist of allowed redirect URLs. Allowlisting redirect URLs is important to prevent malicious actors from pretending to be your application. The redirect includes data in the URL (such as user id and token), either in the location hash, query parameters, or both.
应用处理重定向:重定向由应用处理,并从重定向 URL 解析数据。
¥App handles redirect: the redirect is handled by the app and data is parsed from the redirect URL.
¥Security considerations
切勿将任何密钥放入应用代码中,这样做没有安全的方法!相反,你应该将密钥存储在服务器上,并公开一个端点,该端点为你的客户端进行 API 调用并将数据传回。
¥Never put any secret keys inside your application code, there is no secure way to do this! Instead, you should store your secret key(s) on a server and expose an endpoint that makes API calls for your client and passes the data back.
import * as AuthSession from 'expo-auth-session';
useAuthRequest(config, discovery)
Name | 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({ ... }, { ... });
useAutoDiscovery(issuerOrDiscovery)
Name | 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');
AccessTokenRequest
Type: Class extends TokenRequest<AccessTokenRequestConfig>
implements AccessTokenRequestConfig
Access token request. Exchange an authorization code for a user access token.
AccessTokenRequest Properties
AccessTokenRequest Methods
getHeaders()
AuthError
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
code
Type: string
description
Optional • Type: string
Used to assist the client developer in understanding the error that occurred.
info
Optional • Type: any
uri
Optional • Type: string
A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.
AuthRequest
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
codeVerifier
Optional • Type: string
url
Type: null | string
• Default: null
AuthRequest Methods
makeAuthUrlAsync(discovery)
Name | Type |
---|---|
discovery | AuthDiscoveryDocument |
Create the URL for authorization.
Promise<string>
promptAsync(discovery, promptOptions)
Name | Type |
---|---|
discovery | AuthDiscoveryDocument |
promptOptions (optional) | AuthRequestPromptOptions |
Prompt a user to authorize for a code.
RefreshTokenRequest
Type: Class extends TokenRequest<RefreshTokenRequestConfig>
implements RefreshTokenRequestConfig
Refresh request.
RefreshTokenRequest Properties
RefreshTokenRequest Methods
getHeaders()
RevokeTokenRequest
Type: Class extends Request<RevokeTokenRequestConfig, boolean>
implements RevokeTokenRequestConfig
Revocation request for a given token.
RevokeTokenRequest Methods
getHeaders()
TokenError
Type: Class extends ResponseError
TokenError Properties
code
Type: string
description
Optional • Type: string
Used to assist the client developer in understanding the error that occurred.
info
Optional • Type: any
uri
Optional • Type: string
A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error.
TokenResponse
Type: Class implements TokenResponseConfig
Token Response.
TokenResponse Methods
fromQueryParams(params)
Name | Type |
---|---|
params | Record<string, any> |
Creates a TokenResponse
from query parameters returned from an AuthRequest
.
isTokenFresh(token, secondsMargin)
Name | Type |
---|---|
token | Pick<TokenResponse, 'expiresIn' | 'issuedAt'> |
secondsMargin (optional) | number |
Determines whether a token refresh request must be made to refresh the tokens
boolean
refreshAsync(config, discovery)
Name | Type |
---|---|
config | Omit<TokenRequestConfig, 'grantType' | 'refreshToken'> |
discovery | Pick<DiscoveryDocument, 'tokenEndpoint'> |
shouldRefresh()
boolean
AuthSession.exchangeCodeAsync(config, discovery)
Name | 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.
Returns a discovery document with a valid tokenEndpoint
URL.
AuthSession.fetchDiscoveryAsync(issuer)
Name | Type | Description |
---|---|---|
issuer | string | An |
Fetch a DiscoveryDocument
from a well-known resource provider that supports auto discovery.
Returns a discovery document that can be used for authentication.
AuthSession.fetchUserInfoAsync(config, discovery)
Name | Type | Description |
---|---|---|
config | Pick<TokenResponse, 'accessToken'> | The |
discovery | Pick<DiscoveryDocument, 'userInfoEndpoint'> | The |
Fetch generic user info from the provider's OpenID Connect userInfoEndpoint
(if supported).
Promise<Record<string, any>>
See: UserInfo.
AuthSession.generateHexStringAsync(size)
Name | Type |
---|---|
size | number |
Digest a random string with hex encoding, useful for creating nonce
s.
Promise<string>
AuthSession.getDefaultReturnUrl(urlPath, options)
Name | Type |
---|---|
urlPath (optional) | string |
options (optional) | Omit<CreateURLOptions, 'queryParams'> |
string
Deprecated Use
makeRedirectUri()
instead.
AuthSession.getRedirectUrl(path)
Name | 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
AuthSession.loadAsync(config, issuerOrDiscovery)
Name | Type | Description |
---|---|---|
config | AuthRequestConfig | A valid |
issuerOrDiscovery | IssuerOrDiscovery | A loaded |
Build an AuthRequest
and load it before returning.
Returns an instance of AuthRequest
that can be used to prompt the user for authorization.
AuthSession.makeRedirectUri(options)
Name | 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
AuthSession.refreshAsync(config, discovery)
Name | 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
.Returns a discovery document with a valid tokenEndpoint
URL.
See: Section 6.
AuthSession.resolveDiscoveryAsync(issuerOrDiscovery)
Name | Type |
---|---|
issuerOrDiscovery | IssuerOrDiscovery |
Utility method for resolving the discovery document from an issuer or object.
AuthSession.revokeAsync(config, discovery)
Name | 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.
AccessTokenRequestConfig
Extends: TokenRequestConfig
Config used to exchange an authorization code for an access token.
See: Section 4.1.3
AccessTokenRequestConfig Properties
Name | Type | Description |
---|---|---|
code | string | The authorization code received from the authorization server. |
redirectUri | string | If the |
AuthRequestConfig
Represents an OAuth authorization request as JSON.
AuthRequestConfig Properties
Name | 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 | 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) | string | Specifies what is returned from the authorization server. Default: ResponseType.Code |
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 |
DiscoveryDocument
DiscoveryDocument Properties
Name | 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. |
Deprecated See Facebook authentication.
FacebookAuthRequestConfig
Extends: ProviderAuthRequestConfig
FacebookAuthRequestConfig Properties
Name | Type | Description |
---|---|---|
androidClientId (optional) | string | Android native client ID for use in development builds and bare workflow. |
iosClientId (optional) | string | iOS native client ID for use in development builds and bare workflow. |
webClientId (optional) | string | Expo web client ID for use in the browser. |
Deprecated See Google authentication.
GoogleAuthRequestConfig
Extends: ProviderAuthRequestConfig
GoogleAuthRequestConfig Properties
Name | Type | Description |
---|---|---|
androidClientId (optional) | string | Android native client ID for use in standalone, and bare workflow. |
iosClientId (optional) | string | iOS native client ID for use in standalone, bare workflow, and custom clients. |
language (optional) | string | Language code ISO 3166-1 alpha-2 region code, such as 'it' or 'pt-PT'. |
loginHint (optional) | string | If the user's email address is known ahead of time, it can be supplied to be the default option. If the user has approved access for this app in the past then auth may return without any further interaction. |
selectAccount (optional) | boolean | When Default: false. |
shouldAutoExchangeCode (optional) | boolean | Should the hook automatically exchange the response code for an authentication token. Defaults to |
webClientId (optional) | string | Expo web client ID for use in the browser. |
RefreshTokenRequestConfig
Extends: TokenRequestConfig
Config used to request a token refresh, or code exchange.
See: Section 6
RefreshTokenRequestConfig Properties
Name | Type | Description |
---|---|---|
refreshToken (optional) | string | The refresh token issued to the client. |
RevokeTokenRequestConfig
Extends: Partial<TokenRequestConfig>
Config used to revoke a token.
See: Section 2.1
RevokeTokenRequestConfig Properties
Name | Type | Description |
---|---|---|
token | string | The token that the client wants to get revoked. |
tokenTypeHint (optional) | TokenTypeHint | A hint about the type of the token submitted for revocation. |
ServerTokenResponseConfig
Object returned from the server after a token response.
ServerTokenResponseConfig Properties
Name | Type | Description |
---|---|---|
access_token | string | - |
expires_in (optional) | number | - |
id_token (optional) | string | - |
issued_at (optional) | number | - |
refresh_token (optional) | string | - |
scope (optional) | string | - |
token_type (optional) | TokenType | - |
TokenRequestConfig
Config used to request a token refresh, revocation, or code exchange.
TokenRequestConfig Properties
Name | 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. |
extraParams (optional) | Record<string, string> | Extra query params that'll be added to the query string. |
scopes (optional) | string[] | List of strings to request access to. |
TokenResponseConfig
TokenResponseConfig Properties
Name | Type | Description |
---|---|---|
accessToken | string | The access token issued by the authorization server. |
expiresIn (optional) | number | The lifetime in seconds of the access token. For example, the value If omitted, the authorization server should provide the expiration time via other means or document the default value. |
idToken (optional) | string | ID Token value associated with the authenticated session. |
issuedAt (optional) | number | Time in seconds when the token was received by the client. |
refreshToken (optional) | string | The refresh token, which can be used to obtain new access tokens using the same authorization grant. |
scope (optional) | string | The scope of the access token. Only required if it's different to the scope that was requested by the client. |
state (optional) | string | Required if the "state" parameter was present in the client authorization request. The exact value received from the client. |
tokenType (optional) | TokenType | The type of the token issued. Value is case insensitive. |
AuthRequestPromptOptions
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:
Name | 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 |
AuthSessionOptions
Name | Type | Description |
---|---|---|
authUrl | string | The URL that points to the sign in page that you would like to open the user to. |
projectNameForProxy (optional) | string | Project name to use for the |
returnUrl (optional) | string | The URL to return to the application. In managed apps, it's optional and defaults to output of |
showInRecents (optional) | boolean | Only for: Android A boolean determining whether browsed website should be shown as separate entry in Android recents/multitasking view. Default: false |
AuthSessionRedirectUriOptions
Options passed to makeRedirectUri
.
Name | 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 |
AuthSessionResult
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:
Name | Type | Description |
---|---|---|
type | 'cancel' | 'dismiss' | 'opened' | 'locked' | How the auth completed. |
Name | 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 |
Issuer
URL using the https
scheme with no query or fragment component that the OP asserts as its Issuer Identifier.
Type: string
ProviderMetadata
OpenID Providers have metadata describing their configuration. ProviderMetadata
Type: Record<string, string | boolean | string[]>
ProviderMetadataEndpoints
extended by:
Name | Type | Description |
---|---|---|
backchannel_logout_session_supported (optional) | boolean | - |
backchannel_logout_supported (optional) | boolean | - |
check_session_iframe (optional) | string | - |
claim_types_supported (optional) | string[] | a list of the Claim Types that the OpenID Provider supports. |
claims_locales_supported (optional) | string[] | Languages and scripts supported for values in Claims being returned. |
claims_parameter_supported (optional) | boolean | Boolean value specifying whether the OP supports use of the claims parameter, with Default: false |
claims_supported (optional) | string[] | a list of the Claim Names of the Claims that the OpenID Provider may be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list. |
code_challenge_methods_supported (optional) | CodeChallengeMethod[] | - |
display_values_supported (optional) | string[] | a list of the |
frontchannel_logout_session_supported (optional) | boolean | - |
frontchannel_logout_supported (optional) | boolean | - |
grant_types_supported (optional) | string[] | JSON array containing a list of the OAuth 2.0 Grant Type values that this OP supports. Dynamic OpenID Providers MUST support the authorization_code and implicit Grant Type values and MAY support other Grant Types. If omitted, the default value is ["authorization_code", "implicit"]. |
id_token_signing_alg_values_supported (optional) | string[] | JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT. The algorithm RS256 MUST be included. |
jwks_uri (optional) | string | URL of the OP's JSON Web Key Set JWK document. |
op_policy_uri (optional) | string | URL that the OpenID Provider provides to the person registering the Client to read about the OP's requirements on how the Relying Party can use the data provided by the OP. The registration process SHOULD display this URL to the person registering the Client if it is given. |
op_tos_uri (optional) | string | URL that the OpenID Provider provides to the person registering the Client to read about OpenID Provider's terms of service. The registration process should display this URL to the person registering the Client if it is given. |
request_parameter_supported (optional) | boolean | Boolean value specifying whether the OP supports use of the request parameter, with Default: false |
request_uri_parameter_supported (optional) | boolean | Whether the OP supports use of the Default: true |
require_request_uri_registration (optional) | boolean | Whether the OP requires any Default: false |
response_modes_supported (optional) | string[] | JSON array containing a list of the OAuth 2.0 |
response_types_supported (optional) | string[] | JSON array containing a list of the OAuth 2.0 |
scopes_supported (optional) | string[] | JSON array containing a list of the OAuth 2.0 RFC6749 scope values that this server supports. |
service_documentation (optional) | string | URL of a page containing human-readable information that developers might want or need to know when using the OpenID Provider. In particular, if the OpenID Provider does not support Dynamic Client Registration, then information on how to register Clients needs to be provided in this documentation. |
subject_types_supported (optional) | string[] | JSON array containing a list of the Subject Identifier types that this OP supports.
Valid types include |
token_endpoint_auth_methods_supported (optional) | ('client_secret_post' | 'client_secret_basic' | 'client_secret_jwt' | 'private_key_jwt' | string)[] | A list of Client authentication methods supported by this Token Endpoint.
If omitted, the default is |
ui_locales_supported (optional) | string[] | Languages and scripts supported for the user interface, represented as a JSON array of BCP47 language tag values. |
TokenType
Literal Type: string
Access token type.
See: Section 7.1
Acceptable values are: 'bearer'
| 'mac'
CodeChallengeMethod
CodeChallengeMethod Values
Plain
CodeChallengeMethod.Plain = "plain"
This should not be used. When used, the code verifier will be sent to the server as-is.
S256
CodeChallengeMethod.S256 = "S256"
The default and recommended method for transforming the code verifier.
GrantType
Grant type values used in dynamic client registration and auth requests.
See: Appendix A.10
GrantType Values
AuthorizationCode
GrantType.AuthorizationCode = "authorization_code"
Used for exchanging an authorization code for one or more tokens.
ClientCredentials
GrantType.ClientCredentials = "client_credentials"
Used for client credentials flow.
RefreshToken
GrantType.RefreshToken = "refresh_token"
Used when exchanging a refresh token for a new token.
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. You should use this in favor of clearing cookies (which is mostly not possible on iOS).
See: Section 3.1.2.1.
Prompt Values
Consent
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
.
Login
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
.
None
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.
SelectAccount
Prompt.SelectAccount = "select_account"
Server should prompt the user to select an account. Can be used to switch accounts.
If it can't obtain an account selection choice made by the user, it must return an error, typically account_selection_required
.
ResponseType
The client informs the authorization server of the desired grant type by using the response type.
See: Section 3.1.1.
ResponseType Values
IdToken
ResponseType.IdToken = "id_token"
A custom registered type for getting an id_token
from Google OAuth.
Token
ResponseType.Token = "token"
For requesting an access token (implicit grant) as described by Section 4.2.1.
TokenTypeHint
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
TokenTypeHint Values
¥Providers
AuthSession 内置了对一些流行提供商的支持,使使用尽可能简单。这些允许你跳过重复的事情,例如定义端点和抽象常见功能(例如 language
)。
¥AuthSession has built-in support for some popular providers to make usage as easy as possible. These allow you to skip repetitive things like defining endpoints and abstract common features like language
.
已弃用:该提供程序已被弃用,并将在未来的 SDK 版本中删除。请参阅 谷歌认证。
import * as Google from 'expo-auth-session/providers/google';
有关使用的更多信息,请参阅指南:谷歌认证。
¥See the guide for more info on usage: Google Authentication.
提供额外的 loginHint
参数。如果提前知道用户的电子邮件地址,则可以将其提供为默认选项。
¥Provides an extra loginHint
parameter. If the user's email address is known ahead of time, it can be supplied to be the default option.
对以下 API 强制执行最小范围,以实现 Firebase 和 Auth0 等服务的最佳使用。
¥Enforces minimum scopes to the following APIs for optimal usage with services like Firebase and Auth0.
['openid', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
默认情况下,授权 code
将自动交换为访问令牌。这可以用 shouldAutoExchangeCode
覆盖。
¥By default, the authorization code
will be automatically exchanged for an access token. This can be overridden with shouldAutoExchangeCode
.
默认使用打包 ID 和包名称进行原生 URI 重定向,而不是反向客户端 ID。
¥Defaults to using the bundle ID and package name for the native URI redirect instead of the reverse client ID.
对隐式和基于 id 令牌的身份验证响应禁用 PKCE。
¥Disables PKCE for implicit and id-token based auth responses.
在网络上,弹出窗口显示针对 Google 登录 UI ({ width: 515, height: 680 }
) 优化的尺寸。
¥On web, the popup is presented with the dimensions that are optimized for the Google login UI ({ width: 515, height: 680 }
).
useAuthRequest()
用于跨平台运行的有态度的 Google 身份验证的钩子。
¥A hook used for opinionated Google authentication that works across platforms.
¥Arguments
配置(GoogleAuthRequestConfig
) - 一个 GoogleAuthRequestConfig
对象,其中包含应支持的每个平台的客户端 ID。
¥config (GoogleAuthRequestConfig
) - A GoogleAuthRequestConfig
object with client IDs for each platform that should be supported.
重定向 Uri 选项 (AuthSessionRedirectUriOptions
) - 用于构造重定向 URI(传递到 makeRedirectUri()
)的可选属性。
¥redirectUriOptions (AuthSessionRedirectUriOptions
) - Optional properties used to construct the redirect URI (passed to makeRedirectUri()
).
¥Returns
请求(GoogleAuthRequest | null
) - 可用于提示用户授权的 GoogleAuthRequest
实例。这将是 null
,直到身份验证请求完成加载。
¥request (GoogleAuthRequest | null
) - An instance of GoogleAuthRequest
that can be used to prompt the user for authorization. This will be null
until the auth request has finished loading.
响应(AuthSessionResult | null
) - 在调用 promptAsync
之前,这是 null
。一旦完成,它将返回有关授权的信息。
¥response (AuthSessionResult | null
) - This is null
until promptAsync
has been invoked. Once fulfilled it will return information about the authorization.
提示异步 (function
) - 调用时,Web 浏览器将打开并提示用户进行身份验证。接受 AuthRequestPromptOptions
对象,其中包含有关如何执行提示的选项。
¥promptAsync (function
) - 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.
discovery
包含用于 Google 身份验证的发现 URL 的 DiscoveryDocument
对象。
¥A DiscoveryDocument
object containing the discovery URLs used for Google auth.
已弃用:该提供程序已被弃用,并将在未来的 SDK 版本中删除。请参阅 脸书认证。
import * as Facebook from 'expo-auth-session/providers/facebook';
默认情况下使用隐式身份验证 (ResponseType.Token
)。
¥Uses implicit auth (ResponseType.Token
) by default.
有关使用的更多信息,请参阅指南:脸书认证。
¥See the guide for more info on usage: Facebook Authentication.
将最小范围强制为 ['public_profile', 'email']
,以实现 Firebase 和 Auth0 等服务的最佳使用。
¥Enforces minimum scopes to ['public_profile', 'email']
for optimal usage with services like Firebase and Auth0.
使用 display=popup
以获得更好的 UI 结果。
¥Uses display=popup
for better UI results.
禁用隐式身份验证响应的 PKCE。
¥Disables PKCE for implicit auth response.
在网络上,弹出窗口的尺寸为 { width: 700, height: 600 }
¥On web, the popup is presented with the dimensions { width: 700, height: 600 }
useAuthRequest()
用于跨平台工作的有态度的 Facebook 身份验证的钩子。
¥A hook used for opinionated Facebook authentication that works across platforms.
¥Arguments
配置(FacebookAuthRequestConfig
) - 一个 FacebookAuthRequestConfig
对象,其中包含应支持的每个平台的客户端 ID。
¥config (FacebookAuthRequestConfig
) - A FacebookAuthRequestConfig
object with client IDs for each platform that should be supported.
重定向 Uri 选项 (AuthSessionRedirectUriOptions
) - 用于构造重定向 URI(传递到 makeRedirectUri()
)的可选属性。
¥redirectUriOptions (AuthSessionRedirectUriOptions
) - Optional properties used to construct the redirect URI (passed to makeRedirectUri()
).
¥Returns
请求(FacebookAuthRequest | null
) - 可用于提示用户授权的 FacebookAuthRequest
实例。这将是 null
,直到身份验证请求完成加载。
¥request (FacebookAuthRequest | null
) - An instance of FacebookAuthRequest
that can be used to prompt the user for authorization. This will be null
until the auth request has finished loading.
响应(AuthSessionResult | null
) - 在调用 promptAsync
之前,这是 null
。一旦完成,它将返回有关授权的信息。
¥response (AuthSessionResult | null
) - This is null
until promptAsync
has been invoked. Once fulfilled it will return information about the authorization.
提示异步 (function
) - 调用时,Web 浏览器将打开并提示用户进行身份验证。接受 AuthRequestPromptOptions
对象,其中包含有关如何执行提示的选项。
¥promptAsync (function
) - 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.
discovery
包含用于 Facebook 身份验证的发现 URL 的 DiscoveryDocument
对象。
¥A DiscoveryDocument
object containing the discovery URLs used for Facebook auth.
¥Advanced usage
¥Filtering out AuthSession events in Linking handlers
你可能想要处理应用中的入站链接的原因有很多,例如推送通知或只是常规深度链接(你可以在 链接指南 中阅读有关此内容的更多信息);身份验证重定向只是深层链接的一种类型,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 guide); 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.
¥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.