找不到授权令牌-Express-JWT和Auth0

时间:2019-08-03 02:21:56

标签: node.js express jwt auth0 auth0-lock

我正在将Auth0集成到MERN Stack应用程序中。流程应如下所示:

  1. 用户单击登录按钮触发Auth0Lock.show()
  2. 用户填写其凭据,然后单击“提交”按钮
  3. 点击该API的回调URL,该URL登录用户并将其重定向回前端应用程序

(到目前为止一切正常。)

  1. 前端从API请求用户信息
  2. 前端接收信息并重定向

这似乎是相当标准的身份验证流程。问题是,当前端向后端询问用户信息时,就会出现错误:

UnauthorizedError: No authorization token was found

我的设置本质上是这样的:

// client-side config
const lock = new Auth0Lock(clientID, domain, {
  auth: {
    responseType: 'token',
    audience: 'https://${domain}/userinfo',
    redirectUrl: API_URL + '/api/users/callback', 
    params: {
      scope: 'openid profile email' // no change
    }
  }
})


// server.js

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// [DB setup]

var sessConfig = {
  secret: "[random string]",
  cookie: {
    sameSite: false
  },
  resave: false,
  saveUninitialized: true
};
if(app.get('env') === 'production') sessConfig.cookie.secure = true;

app.use(session(sessConfig));

const {domain, clientID, clientSecret, callbackURL} = require('./config/auth0');
const passportStrategy = new Auth0Strategy(
  {domain, clientID, clientSecret, callbackURL},
  (accessToken, refreshToken, extraParams, profile, done) => done(null, profile)
)
passport.use(passportStrategy);
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
app.use(passport.initialize());
app.use(passport.session());

// [routing]



// routes/users.js
router.get('/callback', (req, res, next) => {
  passport.authenticate('auth0', (err, user, info) => {
    if(err) return next(err);
    if(!user) return next(info);

    req.logIn(user, err => {
      if(err) return next(err);

      const returnTo = req.session.returnTo;
      delete req.session.returnTo;
      res.redirect(returnTo || clientRootURL + '/callback');
    })
  })(req, res, next);
})

router.get(
  '/current',
  require('cors')(),
  authenticate,
  (req, res) => {
    res.json({
      id: req.user.id,
      name: req.user.name,
      email: req.user.email
    });
  }
);


// authenticate.js
module.exports = jwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${domain}/.well-known/jwks.json`
  }),
  audience: clientID,
  issuer: `https://${domain}/`,
  algorithms: ['RS256']
});

绝大多数直接来自Auth0文档。 登录后,我试图从/ users / current端点获取用户信息,它说找不到授权。有谁知道如何使它工作?

2 个答案:

答案 0 :(得分:0)

您应该调用/ userinfo端点以获取用户配置文件,或从id_token获取信息。看看这个文档

https://auth0.com/docs/api/authentication#get-user-info

答案 1 :(得分:0)

每个经过身份验证的前端调用都应包含:

headers: {
    Authorization: `Bearer ${token}`,
},

token 应该在哪里:

const token = await getAccessTokenSilently();

getAccessTokenSilentlyauth0 库的公共函数。

见:getAccessTokenSilently doc