简体   繁体   English

Auth0 授权后获取用户 email

[英]Auth0 get user email after authorization

I have an application and an api, in terms of auth0, an static frontend and a expressjs backend, in production both are working.我有一个应用程序和一个 api,就 auth0 而言,一个 static 前端和一个 expressjs 后端,在生产中都在工作。 I setup Auth0 and users are able to login with Google accounts.我设置了 Auth0,用户可以使用 Google 帐户登录。

I couldn't get the user's email.我无法获取用户的 email。 I will try to summarize the lines of code that matters我将尝试总结重要的代码行

const jwt = require('express-jwt');
const jwks = require('jwks-rsa');
const jwtAuthz = require('express-jwt-authz');

let jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://myapp-01.us.auth0.com/.well-known/jwks.json`
  }),
  audience: `https://api.myapp.com`,
  issuer: `https://myapp-01.us.auth0.com/`,
  algorithms: ['RS256']
});

const checkClientScopes = jwtAuthz(['openid', 'profile', 'email'], { checkAllScopes: true });

app.use('/users', jwtCheck, checkClientScopes, (req, res) => {
  console.log('*** req.user *** ', req.user)
  res.send({ user: req.user })
})

I have been trying to get the user email, I installed, and then I removed the library express-openid-connect .我一直在尝试让用户 email 安装,然后我删除了库express-openid-connect My guess is I missed an small piece of code that I am missing, or a library I didn't installed我的猜测是我错过了我丢失的一小段代码,或者我没有安装的库

Since I was using express-jwt and jwks-rsa因为我使用的是express-jwtjwks-rsa

I was able to create a function to retrieve the user data, but I need to add axios library to request the /userinfo , after我能够创建一个 function 来检索用户数据,但我需要添加axios库来请求/userinfo ,之后

This is the function I created这是我创建的 function

const jwtUser = async (req, res, next) => {
  const response = await axios.get(req.user.aud[1], { headers: { 'Authorization': req.headers.authorization } });
  req.user = response.data;
  next()
};

Then I am able to get the user data然后我就可以获取用户数据

app.use('/userdata', jwtCheck, jwtUser, (req, res) => {
  console.log('user: ', req.user);
  res.send(JSON.stringify(req.user));
})

Hopefully it will be useful for someone else希望它对其他人有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM