跳到主要内容

认证

注册新用户,并通过密码、OTP 或 OAuth 登录。

备注

请先配置 ESPRMBase。authInstance 通过 ESPRMBase.getAuthInstance() 获取。登录成功后返回 userInstance (ESPRMUser),用于设备和群组 API。

本模块的功能​

通过 ESPRMAuth 处理注册和登录:邮箱/用户名注册及验证、密码登录、OTP 登录以及第三方 OAuth 登录。

登录后的忘记密码和修改密码操作,请参阅 密码。

预期结果:获得包含有效会话令牌的 ESPRMUser 实例。

常见工作流​

获取认证实例​

const authInstance = ESPRMBase.getAuthInstance();

用户注册​

await authInstance.sendSignUpCode(username, password);
await authInstance.confirmSignUp(username, verificationCode);

用户登录​

密码登录:

const userInstance = await authInstance.login(username, password);

OTP 登录(两步):

const sessionToken = await authInstance.requestLoginOTP(username);
const userInstance = await authInstance.loginWithOTP(
username,
verificationCode,
sessionToken
);

OAuth 登录:

const userInstance = await authInstance.loginWithOauth("Google");

有效的身份提供商标识符:"Google" · "GitHub" · "SignInWithApple"。请在快速入门中配置 authUrl、clientId、redirectUrl 和 oauthAdapter,详见下文的进阶概念。

错误处理​

try {
const userInstance = await authInstance.login(username, password);
} catch (error) {
console.error("Login failed:", error);
}

常见问题:注册未确认、OTP 或会话令牌有误、缺少 OAuth 适配器或重定向配置。

进阶概念​

OAuth 配置​

important

调用 loginWithOauth 之前,请在 ESPRMBase.configure() 中设置:

  • authUrl、clientId、redirectUrl
  • oauthAdapter(适配器)

各平台重定向 URI:Android · iOS

有效的 OAuth 身份提供商标识符​

向 loginWithOauth() 传入以下字符串值之一:

"Google"          // ESPIdProvider.GOOGLE
"GitHub" // ESPIdProvider.GITHUB
"SignInWithApple" // ESPIdProvider.SIGN_IN_WITH_APPLE

最佳实践​

  1. 持久化会话:使用存储适配器,确保应用重启后 getLoggedInUser() 仍然可用
  2. 保留 OTP 会话令牌:从 requestLoginOTP 获取后保留,直至 loginWithOTP 完成
  3. 不要在客户端代码中嵌入 OAuth 密钥:clientId 应通过构建时配置传入
  4. 及时跳转到登录页面:当 getLoggedInUser() 返回 null 时

相关资源​

On this page