You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Auth0 SPA+API架构中,如何在Node.js后端获取用户邮箱、手机号?

如何在Node.js后端通过Auth0获取用户邮箱和手机号?

问题背景

React端已配置Auth0 Provider:

<Auth0Provider
  domain="xxx.us.auth0.com"
  clientId="xxxxxx"
  authorizationParams={{
    redirect_uri: window.location.origin,
    audience: 'api.xxxx',
    scope: 'openid profile email',
  }}
>
  <App />
</Auth0Provider>

Node.js后端使用express-oauth2-jwt-bearer配置了verifyAuth中间件:

import { auth } from 'express-oauth2-jwt-bearer';

const verifyAuth = auth({
  audience: 'api.xxxx',
  issuerBaseURL: 'https://xxxx.us.auth0.com/',
  tokenSigningAlg: 'RS256',
});

export default verifyAuth;

现在需要实现findOrCreate功能,但通过中间件后req.auth中缺少用户邮箱和手机号,需解决如何在后端获取这些字段。

解决方案

1. 更新前端Auth0授权范围(Scope)

确保请求的权限范围包含需要的字段,若要获取手机号,需在scope中添加phone:

<Auth0Provider
  domain="xxx.us.auth0.com"
  clientId="xxxxxx"
  authorizationParams={{
    redirect_uri: window.location.origin,
    audience: 'api.xxxx',
    scope: 'openid profile email phone', // 添加phone scope
  }}
>
  <App />
</Auth0Provider>

2. 在Auth0控制台配置Token自定义声明

默认情况下,Access Token不会包含用户的邮箱、手机号等详细信息,需通过Auth0的Actions将这些字段注入到Access Token中:

  1. 登录Auth0控制台,进入「Actions」→「Flows」→「Login」
  2. 点击「+ Add Action」→「Build Custom」,创建一个自定义登录Action
  3. 粘贴以下代码(替换自定义命名空间为你的专属域名,避免声明冲突):
exports.onExecutePostLogin = async (event, api) => {
  // 自定义命名空间,必须是URL格式
  const namespace = 'https://your-api-domain.com/';
  
  if (event.authorization) {
    // 将邮箱注入Access Token
    if (event.user.email) {
      api.accessToken.setCustomClaim(`${namespace}email`, event.user.email);
    }
    // 将手机号注入Access Token(需用户已验证手机号)
    if (event.user.phone_number) {
      api.accessToken.setCustomClaim(`${namespace}phone`, event.user.phone_number);
    }
  }
};
  1. 保存并发布该Action,将其添加到登录流程中并启用

3. 后端获取字段

配置完成后,请求经过verifyAuth中间件时,req.auth会包含自定义声明的字段,可直接提取使用:

app.get('/your-endpoint', verifyAuth, (req, res) => {
  const namespace = 'https://your-api-domain.com/';
  const userEmail = req.auth[`${namespace}email`];
  const userPhone = req.auth[`${namespace}phone`];
  
  // 这里执行findOrCreate逻辑
  res.json({ email: userEmail, phone: userPhone });
});

注意事项

  • 手机号字段phone_number仅在用户已验证手机号时存在,需确保用户在Auth0中完成手机号验证
  • 自定义命名空间必须是合法的URL格式,不能使用auth0.com等官方域名,避免冲突

内容的提问来源于stack exchange,提问作者lkp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:08:27