【发布时间】:2020-07-25 19:29:28
【问题描述】:
对于Node JS 上的JWT,我很难让事情按应有的方式工作。
首先让我说我的目标是(登录后)访问我的 API 的 privateRoute 路由。
我总是打:
authHeader == null
在 authenticateToken 中间件函数内部,虽然我已经尝试了很多东西。
所以我无法通过 authenticateToken 的级别让我进入。 作为在标题中引入所需内容并能够通过的解决方案,我曾考虑创建一种进入路径以进入,但它仍然无法正常工作。
这里是相关代码。
app.get('/privateRoute', authenticateToken, function(req, res) {
// Useful work to do, after logging in.
.......
});
function authenticateToken(req, res, next) {
// Gather the jwt access token from the request header
const authHeader = req.headers['authorization'],
token = authHeader && authHeader.split(' ')[1]
if (token == null) {
console.log('authenticateToken-401')
return res.sendStatus(401) // There isn't any token.
}
// It never reaches this point !!!
jwt.verify(token, 'myBigSecret', (err, user) => {
console.log(err)
if (err) {
console.log('authenticateToken-403')
return res.sendStatus(403)
}
req.user = user
})
}
app.get('/entryRoute', function(req, res) {
res.set('authorization', 'Bearer ' + myJWT_Token);
res.redirect('/privateRoute');
});
有人能告诉我我需要对代码进行哪些更改以使我的(可能不太好的)解决方案能够正常工作吗?或者告诉我一个更好的方法?
以下是来自浏览器的一些额外信息,以备不时之需。
在 FireFox 菜单、工具、Web 开发人员、Web 控制台中;网络选项卡。我可以看到以下内容:
对于响应头(/entryRoute):
Authorization : Bearer eyiwhfehihinR…CuwfihvihiL_hfgSt_J8D
Connection :keep-alive
Content-Length : 56
Content-Type : text/html; charset=utf-8
Date : Mon, 13 Apr 2020 09:46:55 GMT
Location : /privateRoute
Server : Xoibuy
Vary : Accept
Via : 1.1 vegur
X-Powered-By : Express
对于请求头(/privateRoute):
Accept : text/html,application/xhtml+xm…ml;q=0.9,image/webp,*/ *;q=0.8
Accept-Encoding : gzip, deflate, br
Accept-Language : en-US,en;q=0.5
Connection : keep-alive
Host : myapp.herokuapp.com
Upgrade-Insecure-Requests : 1
User-Agent : Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/75.0
【问题讨论】:
-
你能分享开发者工具的网络选项卡中的请求信息或请求对象的值吗?
-
我刚刚添加了一些可以在浏览器中找到的信息,希望这是您需要的。请再看一遍帖子,接近尾声。
-
我可以看到我对Authorization所做的事情并没有传递给privateRoute。这可能只是表明我的做法是错误的。
-
您必须将 Authorization 标头传递给您的 http 请求,以使其通过您的 AuthenticateToken 中间件
-
尝试访问它:
req.header('Authorization')。此外,您需要在验证后致电next()以使其进入您的功能
标签: javascript node.js jwt authorization middleware