Javascript express jwt身份验证中间件不工作
我正在使用Javascript express jwt身份验证中间件不工作,javascript,node.js,authentication,express,mean-stack,Javascript,Node.js,Authentication,Express,Mean Stack,我正在使用expressjwt进行一次提示,下面是我的代码: api>routes/index.js: var express = require('express'); var router = express.Router(); var jwt = require('express-jwt'); var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth' }); 之后,当我在中使用auth中间件时 router.po
expressjwt
进行一次提示,下面是我的代码:
api>routes/index.js
:
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth' });
之后,当我在中使用auth
中间件时
router.post('/locations/:locationId/reviews', auth, ctrlReviews.reviewsCreate);
route,当要使用post man发布审查数据时,请求转到加载,并且不显示响应,但如果从route request中删除auth
,则给出响应。
我也和你核实过了
var auth = jwt({
secret: process.env.JWT_SECRET,
userProperty: 'payload'
});
正如注释中提到的,您正在尝试处理有效和无效的令牌。这应该是可能的,类似于下面的代码 如果您使用Postman以以下标题调用此消息,那么您将收到200 OK,并显示一条消息“OK!”
Authorization: Bearer validJWT
如果您使用邮递员在没有有效JWT的情况下呼叫此邮件,则您将收到401 Unauthorized,并显示“无效令牌…”消息
var jsonwebtoken = require('jsonwebtoken');
var express = require('express');
var app = express();
var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth'});
// Generate valid JWT
console.log(jsonwebtoken.sign({ foo: 'bar' }, 'thisIsSecret'));
app.post('/locations/:locationId/reviews', auth, function(req, res, next) {
// Log user details set in JWT
console.log(req.auth)
res.send('OK!');
});
// Handle invalid JWT
app.use(function(err, req, res, next) {
if (err.constructor.name === 'UnauthorizedError') {
res.status(401).send('invalid token...');
}
});
app.listen(3000, function() {
console.log('Server running on 3000')
})
你的快速jwt逻辑适合我。您是否在Postman的授权头中发送了有效的JWT?@dan我想检查
UnauthorizederRor
,并在app.js
中捕获它,类似于app.use(函数(err,req,res,next){if(err.name=='UnauthorizederRor'){res.status(401);res.json(“message:+err.name+”:“+err.message”); } });
并期待消息响应。@dan抱歉,再次检查我在app.js
(UnauthorizedErorr
)中有一个类型错误。谢谢uOk,我已经发布了一个答案来展示一个例子。希望这能有所帮助。