Reference version

Expo AppleAuthentication

一个为 iOS 提供“使用 Apple 登录”功能的库。

iOS
tvOS
Included in Expo Go
Bundled version:
~55.0.0

For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.

expo-apple-authentication 为 iOS 提供 Apple 认证。它目前还不支持 Android 或 web。

任何包含第三方身份验证选项的应用必须提供 Apple 认证作为一种选项,以符合 App Store 审核指南。有关更多信息,请参阅 Sign In with Apple 网站上的 Apple 认证。

安装

Terminal
npx expo install expo-apple-authentication

If you are installing this in an existing React Native app, make sure to install expo in your project.

在 app 配置中进行配置

如果你在项目中使用配置插件(Continuous Native Generation (CNG)),你可以使用 expo-apple-authentication 内置的 config plugin 来进行配置。该插件允许你配置各种无法在运行时设置、且需要构建新的应用二进制文件后才会生效的属性。如果你的应用使用 CNG,那么你需要手动配置该库。

设置 iOS 项目

要在你的应用中启用 Sign In with Apple 能力,请在项目的 app 配置中将 ios.usesAppleSignIn 属性设为 true

app.json
{ "expo": { "ios": { "usesAppleSignIn": true } } }

Example app.json with config plugin

在本地运行 EAS Build 将在构建前使用 iOS capabilities signing 来启用所需的能力。

app.json
{ "expo": { "plugins": ["expo-apple-authentication"] } }
Are you using this library in an existing React Native app?

不使用 EAS Build 的应用必须为其 bundle identifier 手动配置 Apple Sign In 能力。

如果你通过 Apple Developer Console 启用了 Apple Sign In 能力,那么请务必在 ios/[app]/[app].entitlements 文件中添加以下 entitlement:

<key>com.apple.developer.applesignin</key> <array> <string>Default</string> </array>

另外,请在你的 ios/[app]/Info.plist 中将 CFBundleAllowMixedLocalizations 设为 true,以确保登录按钮使用设备语言环境。

用法

Apple Authentication Usage
import * as AppleAuthentication from 'expo-apple-authentication'; import { View, StyleSheet } from 'react-native'; export default function App() { return ( <View style={styles.container}> <AppleAuthentication.AppleAuthenticationButton buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN} buttonStyle={AppleAuthentication.AppleAuthenticationButtonStyle.BLACK} cornerRadius={5} style={styles.button} onPress={async () => { try { const credential = await AppleAuthentication.signInAsync({ requestedScopes: [ AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL, ], }); // 已登录 } catch (e) { if (e.code === 'ERR_REQUEST_CANCELED') { // 处理用户取消登录流程的情况 } else { // 处理其他错误 } } }} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, button: { width: 200, height: 44, }, });

开发与测试

你可以在 iOS 上的 Expo Go 中测试这个库,而无需遵循上述任何说明。 不过,如果你使用的是 EAS Build,则需要添加 config plugin 才能使用这个库。 当你登录 Expo Go 时,你收到的标识符和值很可能会与你在独立应用中收到的不同。

你可以在 iOS 模拟器上对这个库进行有限测试。不过,并非所有方法的表现都会与真机相同, 因此我们强烈建议在开发过程中尽可能使用真机进行测试。

验证来自 Apple 的响应

Apple 的响应包含一个带有用户信息的已签名 JWT。为了确保该响应确实来自 Apple, 你可以使用 Apple 的公钥对签名进行加密验证,该公钥发布在 https://appleid.apple.com/auth/keys。 此过程并不特定于 Expo。

API

import * as AppleAuthentication from 'expo-apple-authentication';

Component

AppleAuthenticationButton

iOS
tvOS

Type: React.Element<AppleAuthenticationButtonProps>

This component displays the proprietary "Sign In with Apple" / "Continue with Apple" button on your screen. The App Store Guidelines require you to use this component to start the authentication process instead of a custom button. Limited customization of the button is available via the provided properties.

You should only attempt to render this if AppleAuthentication.isAvailableAsync() resolves to true. This component will render nothing if it is not available, and you will get a warning in development mode (__DEV__ === true).

The properties of this component extend from View; however, you should not attempt to set backgroundColor or borderRadius with the style property. This will not work and is against the App Store Guidelines. Instead, you should use the buttonStyle property to choose one of the predefined color styles and the cornerRadius property to change the border radius of the button.

Make sure to attach height and width via the style props as without these styles, the button will not appear on the screen.

See: Apple Documentation for more details.

AppleAuthenticationButtonProps

buttonStyle

iOS
tvOS

The Apple-defined color scheme to use to display the button.

buttonType

iOS
tvOS

The type of button text to display ("Sign In with Apple" vs. "Continue with Apple").

cornerRadius

iOS
tvOS
Optional • Type: number

The border radius to use when rendering the button. This works similarly to style.borderRadius in other Views.

onPress

iOS
tvOS
Type: () => void

The method to call when the user presses the button. You should call AppleAuthentication.signInAsync in here.

style

iOS
tvOS
Optional • Type: StyleProp<Omit<ViewStyle, 'backgroundColor' | 'borderRadius'>>

The custom style to apply to the button. Should not include backgroundColor or borderRadius properties.

Inherited Props

Methods

AppleAuthentication.formatFullName(fullName, formatStyle)

iOS
tvOS
ParameterTypeDescription
fullNameAppleAuthenticationFullName

The full name object with the tokenized portions

formatStyle(optional)AppleAuthenticationFullNameFormatStyle

The style in which the name should be formatted


Creates a locale-aware string representation of a person's name from an object representing the tokenized portions of a user's full name

Returns:
string

A locale-aware string representation of a person's name

AppleAuthentication.getCredentialStateAsync(user)

iOS
tvOS
ParameterTypeDescription
userstring

The unique identifier for the user whose credential state you'd like to check. This should come from the user field of an AppleAuthenticationCredential object.


Queries the current state of a user credential, to determine if it is still valid or if it has been revoked.

Note: This method must be tested on a real device. On the iOS simulator it always throws an error.

A promise that fulfills with an AppleAuthenticationCredentialState value depending on the state of the credential.

AppleAuthentication.isAvailableAsync()

iOS
tvOS

Determine if the current device's operating system supports Apple authentication.

Returns:
Promise<boolean>

A promise that fulfills with true if the system supports Apple authentication, and false otherwise.

AppleAuthentication.refreshAsync(options)

iOS
tvOS

An operation that refreshes the logged-in user’s credentials. Calling this method will show the sign in modal before actually refreshing the user credentials.

A promise that fulfills with an AppleAuthenticationCredential object after a successful authentication, and rejects with ERR_REQUEST_CANCELED if the user cancels the refresh operation.

AppleAuthentication.signInAsync(options)

iOS
tvOS
ParameterTypeDescription
options(optional)AppleAuthenticationSignInOptions

Sends a request to the operating system to initiate the Apple authentication flow, which will present a modal to the user over your app and allow them to sign in.

You can request access to the user's full name and email address in this method, which allows you to personalize your UI for signed in users. However, users can deny access to either or both of these options at runtime.

Additionally, you will only receive Apple Authentication Credentials the first time users sign into your app, so you must store it for later use. It's best to store this information either server-side, or using SecureStore, so that the data persists across app installs. You can use AppleAuthenticationCredential.user to identify the user, since this remains the same for apps released by the same developer.

A promise that fulfills with an AppleAuthenticationCredential object after a successful authentication, and rejects with ERR_REQUEST_CANCELED if the user cancels the sign-in operation.

AppleAuthentication.signOutAsync(options)

iOS
tvOS

An operation that ends the authenticated session. Calling this method will show the sign in modal before actually signing the user out.

It is not recommended to use this method to sign out the user as it works counterintuitively. Instead of using this method it is recommended to simply clear all the user's data collected from using signInAsync or refreshAsync methods.

A promise that fulfills with an AppleAuthenticationCredential object after a successful authentication, and rejects with ERR_REQUEST_CANCELED if the user cancels the sign-out operation.

Event Subscriptions

AppleAuthentication.addRevokeListener(listener)

iOS
tvOS
ParameterType
listener() => void

Returns:
EventSubscription

Interfaces

Subscription

iOS
tvOS

A subscription object that allows to conveniently remove an event listener from the emitter.

Subscription Methods

remove()

iOS
tvOS

Removes an event listener for which the subscription has been created. After calling this function, the listener will no longer receive any events from the emitter.

Returns:
void

Types

AppleAuthenticationCredential

iOS
tvOS

The object type returned from a successful call to AppleAuthentication.signInAsync(), AppleAuthentication.refreshAsync(), or AppleAuthentication.signOutAsync() which contains all of the pertinent user and credential information.

See: Apple Documentation for more details.

PropertyTypeDescription
authorizationCodestring | null

A short-lived session token used by your app for proof of authorization when interacting with the app's server counterpart. Unlike user, this is ephemeral and will change each session.

emailstring | null

The user's email address. Might not be present if you didn't request the EMAIL scope. May also be null if this is not the first time the user has signed into your app. If the user chose to withhold their email address, this field will instead contain an obscured email address with an Apple domain.

fullNameAppleAuthenticationFullName | null

The user's name. May be null or contain null values if you didn't request the FULL_NAME scope, if the user denied access, or if this is not the first time the user has signed into your app.

identityTokenstring | null

A JSON Web Token (JWT) that securely communicates information about the user to your app.

realUserStatusAppleAuthenticationUserDetectionStatus

A value that indicates whether the user appears to the system to be a real person.

statestring | null

An arbitrary string that your app provided as state in the request that generated the credential. Used to verify that the response was from the request you made. Can be used to avoid replay attacks. If you did not provide state when making the sign-in request, this field will be null.

userstring

An identifier associated with the authenticated user. You can use this to check if the user is still authenticated later. This is stable and can be shared across apps released under the same development team. The same user will have a different identifier for apps released by other developers.

AppleAuthenticationFullName

iOS
tvOS

An object representing the tokenized portions of the user's full name. Any of all of the fields may be null. Only applicable fields that the user has allowed your app to access will be nonnull.

PropertyTypeDescription
familyNamestring | null
-
givenNamestring | null
-
middleNamestring | null
-
namePrefixstring | null
-
nameSuffixstring | null
-
nicknamestring | null
-

AppleAuthenticationFullNameFormatStyle

iOS
tvOS

Literal Type: string

A value to specify the style for formatting a name.

See: Apple Documentation for more details.

Acceptable values are: 'default' | 'short' | 'medium' | 'long' | 'abbreviated'

AppleAuthenticationRefreshOptions

iOS
tvOS

The options you can supply when making a call to AppleAuthentication.refreshAsync(). You must include the ID string of the user whose credentials you'd like to refresh.

See: Apple Documentation for more details.

PropertyTypeDescription
requestedScopes(optional)AppleAuthenticationScope[]

Array of user information scopes to which your app is requesting access. Note that the user can choose to deny your app access to any scope at the time of logging in. You will still need to handle null values for any scopes you request. Additionally, note that the requested scopes will only be provided to you the first time each user signs into your app; in subsequent requests they will be null. Defaults to [] (no scopes).

state(optional)string

An arbitrary string that is returned unmodified in the corresponding credential after a successful authentication. This can be used to verify that the response was from the request you made and avoid replay attacks. More information on this property is available in the OAuth 2.0 protocol RFC6749.

userstring
-

AppleAuthenticationSignInOptions

iOS
tvOS

The options you can supply when making a call to AppleAuthentication.signInAsync(). None of these options are required.

See: Apple Documentation for more details.

PropertyTypeDescription
nonce(optional)string

An arbitrary string that is used to prevent replay attacks. See more information on this in the OpenID Connect specification.

requestedScopes(optional)AppleAuthenticationScope[]

Array of user information scopes to which your app is requesting access. Note that the user can choose to deny your app access to any scope at the time of logging in. You will still need to handle null values for any scopes you request. Additionally, note that the requested scopes will only be provided to you the first time each user signs into your app; in subsequent requests they will be null. Defaults to [] (no scopes).

state(optional)string

An arbitrary string that is returned unmodified in the corresponding credential after a successful authentication. This can be used to verify that the response was from the request you made and avoid replay attacks. More information on this property is available in the OAuth 2.0 protocol RFC6749.

AppleAuthenticationSignOutOptions

iOS
tvOS

The options you can supply when making a call to AppleAuthentication.signOutAsync(). You must include the ID string of the user to sign out.

See: Apple Documentation for more details.

PropertyTypeDescription
state(optional)string

An arbitrary string that is returned unmodified in the corresponding credential after a successful authentication. This can be used to verify that the response was from the request you made and avoid replay attacks. More information on this property is available in the OAuth 2.0 protocol RFC6749.

userstring
-

Enums

AppleAuthenticationButtonStyle

iOS
tvOS

An enum whose values control which pre-defined color scheme to use when rendering an AppleAuthenticationButton.

WHITE

AppleAuthenticationButtonStyle.WHITE = 0

White button with black text.

WHITE_OUTLINE

AppleAuthenticationButtonStyle.WHITE_OUTLINE = 1

White button with a black outline and black text.

BLACK

AppleAuthenticationButtonStyle.BLACK = 2

Black button with white text.

AppleAuthenticationButtonType

iOS
tvOS

An enum whose values control which pre-defined text to use when rendering an AppleAuthenticationButton.

SIGN_IN

AppleAuthenticationButtonType.SIGN_IN = 0

"Sign in with Apple"

CONTINUE

AppleAuthenticationButtonType.CONTINUE = 1

"Continue with Apple"

SIGN_UP

iOS 13.2+
AppleAuthenticationButtonType.SIGN_UP = 2

"Sign up with Apple"

AppleAuthenticationCredentialState

iOS
tvOS

An enum whose values specify state of the credential when checked with AppleAuthentication.getCredentialStateAsync().

See: Apple Documentation for more details.

REVOKED

AppleAuthenticationCredentialState.REVOKED = 0

AUTHORIZED

AppleAuthenticationCredentialState.AUTHORIZED = 1

NOT_FOUND

AppleAuthenticationCredentialState.NOT_FOUND = 2

TRANSFERRED

AppleAuthenticationCredentialState.TRANSFERRED = 3

AppleAuthenticationOperation

iOS
tvOS

IMPLICIT

AppleAuthenticationOperation.IMPLICIT = 0

An operation that depends on the particular kind of credential provider.

LOGIN

AppleAuthenticationOperation.LOGIN = 1

REFRESH

AppleAuthenticationOperation.REFRESH = 2

LOGOUT

AppleAuthenticationOperation.LOGOUT = 3

AppleAuthenticationScope

iOS
tvOS

An enum whose values specify scopes you can request when calling AppleAuthentication.signInAsync().

Note that it is possible that you will not be granted all of the scopes which you request. You will still need to handle null values for any fields you request.

See: Apple Documentation for more details.

FULL_NAME

AppleAuthenticationScope.FULL_NAME = 0

EMAIL

AppleAuthenticationScope.EMAIL = 1

AppleAuthenticationUserDetectionStatus

iOS
tvOS

An enum whose values specify the system's best guess for how likely the current user is a real person.

See: Apple Documentation for more details.

UNSUPPORTED

AppleAuthenticationUserDetectionStatus.UNSUPPORTED = 0

The system does not support this determination and there is no data.

UNKNOWN

AppleAuthenticationUserDetectionStatus.UNKNOWN = 1

The system has not determined whether the user might be a real person.

LIKELY_REAL

AppleAuthenticationUserDetectionStatus.LIKELY_REAL = 2

The user appears to be a real person.

错误代码

大多数错误代码与官方 Apple Authorization errors 相匹配。

代码描述
ERR_INVALID_OPERATION已执行无效的授权操作。
ERR_INVALID_RESPONSE授权请求收到了无效响应。
ERR_INVALID_SCOPE传入了无效的 AppleAuthenticationScope
ERR_REQUEST_CANCELED用户取消了授权尝试。
ERR_REQUEST_FAILED授权尝试失败。有关附加信息,请参阅错误消息。
ERR_REQUEST_NOT_HANDLED授权请求未被正确处理。
ERR_REQUEST_NOT_INTERACTIVE授权请求不是交互式的。
ERR_REQUEST_UNKNOWN授权尝试因未知原因失败。