Docs 菜单

Docs 主页开发应用程序Atlas Device SDKs

对用户进行身份验证 - React Native SDK

在此页面上

  • 先决条件
  • 在客户端中配置用户身份验证
  • 设置 @realm/react 提供者
  • 为 UserProvider 编写后备组件
  • 用户会话
  • 身份验证提供者和客户端身份验证
  • 匿名用户
  • 电子邮件/密码用户
  • API 密钥用户
  • 自定义 JWT 用户
  • 自定义函数用户
  • Facebook 用户
  • Google 用户
  • Apple 用户
  • 离线登录
  • 获取用户访问令牌
  • 刷新令牌有效期
  • 注销用户
  • useAuth 钩子参考文档

@realm/react 具有用于用户身份验证的钩子。 useAuthuseEmailPasswordAuth使用已启用的身份验证提供程序处理身份验证。

有关useAuth的快速参考,请参阅本页上的useAuth 钩子。有关useEmailPasswordAuth快速参考,请参阅“管理电子邮件/密码用户”页面上的useEmailPasswordAuth 钩子

您也可以直接使用 Realm.js API。实例化Credentials对象并将其传递给App.logIn()以进行身份验证并获取User对象。

在对用户进行身份验证之前,您必须:

@realm/react 具有用于用户身份验证的提供者和挂钩。要配置用户身份验证,请执行以下操作:

  1. 设置 @realm/react 提供者。

  2. UserProvider 编写后备组件。

AppProvider包装的组件可以访问useAppuseAuth钩子。仅当AppProvider成功连接到 App Services 后端时,这些组件才会呈现。

UserProvider包装的组件可以使用useUser钩子访问经过身份验证的用户。仅当您的应用具有经过身份验证的用户时,才会呈现这些组件

要配置用户身份验证,请执行以下操作:

  1. 将需要访问 App Services 的所有组件封装在 AppProvider 中。

  2. AppProvider 内部,用 UserProvider 来封装您希望经过身份验证的用户有权访问的所有组件。

  3. UserProvider 中,包含一个 fallback 属性(附带用于用户登录的组件)。如果没有经过身份验证的用户,该应用则会显示此组件。

import React from 'react';
import {AppProvider, UserProvider} from '@realm/react';
// Fallback log in component that's defined in another file.
import {LogIn} from './Login';
export const LoginExample = () => {
return (
<ScrollView>
<AppProvider id={APP_ID}>
{/* If there is no authenticated user, mount the
`fallback` component. When user successfully
authenticates, the app unmounts the `fallback`
component (in this case, the `LogIn` component). */}
<UserProvider fallback={LogIn}>
{/* Components inside UserProvider have access
to the user. These components only mount if
there's an authenticated user. */}
<UserInformation />
</UserProvider>
</AppProvider>
</ScrollView>
);
};

如果您的应用没有一个经过身份验证且为已登录状态的用户,则不会渲染 UserProvider 及其子项。要处理这种情况,您可以向 UserProvider 传递一个后备组件。这通常是应用的登录界面呈现的内容。

以下示例使用匿名身份验证,但您可以使用任何 useAuth 方法。

要为 UserProvider 编写身份验证后备组件,请执行以下操作:

  1. 创建功能组件。

  2. useAuth 挂钩解构 logInWithAnonymousresult

  3. 在具有空依赖项数组的 useEffect 代码块中调用 logInWithAnonymous()

  4. 处理 result。如果身份验证操作不成功,您可以根据 result 编写错误处理。

export const LogIn = () => {
// `logInWithAnonymous` logs in a user using an
// anonymous Realm Credential.
// `result` gives us access to the result of the
// current operation. In this case, `logInWithAnonymous`.
const {logInWithAnonymous, result} = useAuth();
// Log in an anyonmous user on component render.
// On successful login, this fallback component unmounts.
useEffect(() => {
logInWithAnonymous();
}, [])
return (
<View >
{!result.error && <Text>Please log in</Text>}
<View>
{result.pending && <ActivityIndicator />}
{result.error && <ErrorComponent error={result.error} />}
</View>
</View>
);
};

React Native SDK 将与 Atlas App Services 进行通信,以便使用访问令牌和刷新令牌来管理会话。

要了解有关会话管理的更多信息,请参阅 App Services 文档中的用户会话

当您在客户端中配置了用户身份验证,并在您的 App Services App 中配置了身份验证提供者后,便可允许用户登录。

匿名提供程序允许用户使用没有关联信息的临时帐户登录您的应用程序。

在用户当前登录时调用身份验证方法会将当前用户切换为新用户。

如果您在 UserProvider 回退中调用 logInWithAnonymous(),在成功匿名登录后,就会立即呈现 UserProvider 的子项。

要让用户匿名登录,请执行以下操作:

  1. useAuth 挂钩解构 logInWithAnonymousresult

  2. 不带任何参数调用 logInWithAnonymous()

  3. 处理 result

export const LogInWithAnonymous = () => {
const {logInWithAnonymous, result} = useAuth();
const performAnonymousLogin = logInWithAnonymous;
// Handle `result`...
};

电子邮件/密码身份验证提供者允许用户使用电子邮件地址和密码登录您的应用程序。

您可以使用 useEmailPasswordAuth 钩子来处理您客户端中的用户登录。要快速获取 useEmailPasswordAuth 相关参考,请参阅“管理电子邮件/密码用户”页面上的 useEmailPasswordAuth 钩子

若要使用电子邮件地址和密码使某一用户登录:

  1. useEmailPasswordAuth 挂钩解构 logInresult

  2. 将用户的电子邮件地址和密码作为对象传递给 LogIn()

  3. 处理 result

export const LoginWithEmail = () => {
const {logIn, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performLogin = () => {
logIn({email, password});
};
// Handle `result`...
};

API 密钥身份验证提供者允许服务器进程直接或代表用户访问您的应用程序。

要使用 API 密钥进行登录,请使用服务器或用户 API 密钥创建一个 API 密钥档案并将其传递给 App.logIn()

// Get the API key from the local environment
const apiKey = process.env?.appServicesApiKey;
if (!apiKey) {
throw new Error("Could not find a Server API Key.");
}
// Create an api key credential
const credentials = Realm.Credentials.apiKey(apiKey);
const user = await app.logIn(credentials);

自定义 JWT身份验证提供者可使用任何返回JSON Web 令牌的身份验证系统处理用户身份验证。

要让自定义 JWT 用户登录,请执行以下操作:

  1. 在您的 App Services 后端设置 JWT 身份验证提供者。

  2. 从外部系统获取 JWT。

  3. useAuth 挂钩解构 logInWithJWTresult

  4. 将 JWT 传递给 logInWithJWT()

  5. 处理 result

export const LogInWithJWT = () => {
const {logInWithJWT, result} = useAuth();
// Get the current anonymous user so we can call
// an App Services Function later.
const anonymousUser = useUser();
const performJWTLogin = async () => {
// Get a JWT from a provider. In this case, from
// an App Services Function called "generateJWT".
const token = (await anonymousUser.functions.generateJWT()) as string;
logInWithJWT(token);
};
// Handle `result`...
};

自定义函数身份验证提供程序允许您通过运行接收有关用户的任意信息有效负载的函数来处理用户身份验证。有关详细信息,请参阅自定义函数身份验证

要使用自定义函数提供程序让用户登录,请执行以下操作:

  1. 创建一个 App Services 函数以处理您的身份验证需求。

  2. 为您的 App Services App 启用自定义函数提供程序,并将其配置为使用您先前创建的函数。

  3. useAuth 挂钩解构 logInWithFunctionresult

  4. 将任何相关的用户数据(例如用户名)传递给 logInWithFunction()

  5. 处理 result

export const LogInWithFunction = () => {
const {logInWithFunction, result} = useAuth();
const performFunctionLogin = async (email: string, password: string) => {
// Pass arbitrary information to the Atlas function configured
// for your App's Custom Function provider.
logInWithFunction({email, password});
};
// Handle `result`...
};

Facebook身份验证提供者允许您使用用户现有的 Facebook 帐户通过 Facebook 应用对用户进行身份验证。

要使用现有 Facebook 帐户登录用户,您必须为您的 App Services App 配置并启用Facebook 身份验证提供程序。

重要

请勿存储 Facebook 个人资料图片的 URL

Facebook 个人资料图片 URL 包含用户的访问令牌,用于授予该图像的权限。为了确保安全,请勿存储包含用户访问令牌的 URL。相反,在需要获取图像时,可直接从用户的元数据字段访问 URL。

您可以使用 官方 Facebook SDK 处理用户身份验证和来自客户端应用程序的重定向流。完成身份验证后,Facebook SDK 会返回一个访问令牌,您可以将该令牌发送到您的 React Native 应用,并使用该令牌来结束用户登录到您应用的流程。

export const LogInWithFacebook = () => {
const {logInWithFacebook, result} = useAuth();
const performLogin = () => {
// Get an access token using the Facebook SDK.
// You must define this function.
const token = getFacebookToken();
logInWithFacebook(token);
};
// Handle `result`...
};

Google身份验证提供程序允许您使用用户的现有 Google 帐户对用户进行身份验证。

要对 Google 用户进行身份验证,您必须为您的 App Services App 配置Google 身份验证提供者

React Native 没有官方的“使用 Google 登录”集成。使用 Realm 身份验证将“使用 Google 登录”功能集成到您的 React Native 应用中的最简单方法是使用第三方库。您还可以使用 Google Identity Services 构建自己的解决方案 处理用户身份验证和来自客户端应用程序的重定向流。

无论采用何种实现方式,您都必须从 Google 授权服务器检索 ID 令牌。使用该 ID 令牌登录 Realm。

export const LogInWithGoogle = () => {
const {logInWithGoogle, result} = useAuth();
const performLogin = () => {
// Get an access token using a third-party library
// or build your own solution. You must define this function.
const token = getGoogleToken();
logInWithGoogle(token);
};
// Handle `result`...
};

Apple身份验证提供程序允许您通过“使用 Apple 登录”对用户进行身份验证。

要对 Apple 用户进行身份验证,您必须为您的 App Services App 配置Apple 身份验证提供者

您可以使用 官方的 Sign in with Apple JS SDK 处理用户身份验证和来自客户端应用程序的重定向流。完成身份验证后,Apple JS SDK 会返回一个 ID 令牌,您可以将其发送到您的 React Native 应用,并使用它来结束用户登录到您应用的流程。

export const LogInWithApple = () => {
const {logInWithApple, result} = useAuth();
const performLogin = () => {
// Get an access token using the Apple SDK.
// You must define this function.
const token = getAppleToken();
logInWithApple(token);
};
// Handle `result`...
};

提示

如果您收到指示 token contains an invalid number of segmentsLogin failed 错误,请验证您是否传递了 JWT 的 UTF-8 编码字符串版本。

当您的 Realm 应用程序对用户进行身份验证时,它会缓存该用户的档案。您可以检查是否存在现有用户档案以绕过登录流程并访问已缓存的用户。使用它可离线打开一个 Realm。

注意

初始登录需要网络连接

当用户注册您的应用或使用客户端上的现有帐户首次登录时,客户端必须具有网络连接。通过检查是否存在已缓存的用户档案,您可以离线打开 Realm,但前提是用户之前已在线登录。

// Log user into your App Services App.
// On first login, the user must have a network connection.
const getUser = async () => {
// If the device has no cached user credentials, log in.
if (!app.currentUser) {
const credentials = Realm.Credentials.anonymous();
await app.logIn(credentials);
}
// If the app is offline, but credentials are
// cached, return existing user.
return app.currentUser!;
};

要了解如何在同步配置中使用已缓存的用户并在离线时访问 Realm,请阅读离线时打开已同步的 Realm 文档。

当用户登录时,Atlas App Services 会为用户创建一个访问令牌,以为他们授予访问您应用的权限。Realm SDK 会自动管理访问令牌,在访问令牌过期时对其进行刷新,并在每次请求中为当前用户提供有效的访问令牌。Realm 不会自动对刷新令牌进行刷新。当刷新令牌过期后,用户必须重新登录。

如果在 SDK 外部发送请求,则需要在每个请求中包含用户的访问令牌,并在令牌过期时手动刷新令牌。

您可以在 SDK 中,通过用户的 Realm.User 对象来访问和刷新已登录用户的访问令牌,如下例所示:

const RefreshUserAcessToken = () => {
const user = useUser();
const [accessToken, setAccessToken] = useState<string | null>();
// Gets a valid user access token to authenticate requests
const refreshAccessToken = async () => {
// An already logged in user's access token might be stale. To
// guarantee that the token is valid, refresh it if necessary.
await user.refreshCustomData();
setAccessToken(user.accessToken);
};
// Use access token...
};

刷新令牌会在设定的时间段后过期。刷新令牌过期后,访问令牌将无法再刷新,用户必须重新登录。

如果刷新令牌在 Realm 打开后过期,则在用户再次登录之前设备无法进行同步。同步错误处理程序应实现在尝试同步时捕获令牌过期错误的逻辑,然后将用户重定向到登录流程。

有关配置刷新令牌过期的信息,请参阅 App Services 文档中的管理用户会话

若要登出任何用户,请在相应的用户实例上调用 User.logOut() 方法。

警告

当用户注销时,您无法再在用户已打开的任何已同步 Realm 中读取或写入数据。因此,在发起用户注销之前尚未完成的所有操作均无法成功完成,且可能会导致错误。以此方式失败的写入操作中的所有数据都将丢失。

function UserInformation() {
const user = useUser();
const {logOut} = useAuth();
const performLogout = () => {
logOut();
};
// Add UI for logging out...
}

useAuth 钩子为每个 App Services 身份验证提供者提供了一种身份验证方法。它还具有与身份验证相关的状态。有关详细信息,请参阅 useAuth 参考文档。

您还可以查看useAuth@realm/react API 文档。

← 创建和删除用户 - React Native SDK