node.js - 未找到授权令牌 - Express-JWT 和 Auth0
问题描述
我正在将 Auth0 集成到 MERN Stack 应用程序中。流程应如下所示:
- 用户单击触发 Auth0Lock.show() 的登录按钮
- 用户填写他们的凭据并单击提交按钮
- 命中 API 的回调 URL,使用户登录并将其重定向回前端应用程序
(到目前为止,一切看起来都运行良好)
- 前端从 API 请求用户信息
- 前端接收信息并重定向
这似乎是一个相当标准的身份验证流程。问题是前端向后端询问用户信息时,出现错误:
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 端点获取用户信息,它说它找不到授权。有谁知道如何让它工作?
解决方案
每个经过身份验证的前端调用都应包含:
headers: {
Authorization: `Bearer ${token}`,
},
token
应该在哪里:
const token = await getAccessTokenSilently();
getAccessTokenSilently
是auth0
lib 的一个公共函数。
推荐阅读
- reactjs - 未处理的运行时错误:应该有一个队列。这可能是 React 中的一个错误。请提出问题
- css - 在 Tomcat 错误页面中访问外部 css 文件
- php - 将参数动态传递给模型并在视图中显示结果
- sql - Oracle Apex Change IG 列是选择列表以使用 html 表达式
- git - 从企业 gitlab git 克隆到 EC2
- node.js - 返回 hasura 变量时出错 - Auth Webhook - AWS Lambda
- javascript - TypeError:无法在 React Project 中读取 null 的属性“长度”
- git - 如何修复 rebase 上子模块的“add_cacheinfo 无法刷新路径”错误?
- python-3.x - TypeError:使用拆分和拼写时预期的字符串或类似字节的对象
- react-native - 单击时反应原生可触摸不透明度边框颜色变化