我正在尝试实施JWT身份验证。 / login和/ register工作正常,他们返回身份验证令牌,但是当我尝试使用标头GET / secret进行授权时,#Author;' =' JWT token_received',它返回一个未经授权的字符串'我看不到JWTStrategy的记录。请让我知道我哪里出错了。
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = "very_secret"
passport.use(new JwtStrategy(opts, function(payload, next){
console.log("payload received" + payload);
User.findById(payload.id, function(err, user){
console.log("user found:" + user);
if(err){
return next(err, false)
}
else if(user){
return next(null, user)
}
else{
return next(null, false)
}
});
}
));
app.use(passport.initialize());
app.post("/login", function(req, res){
var email = req.body.email;
var password = req.body.password;
var user = User.findOne({"email": email}, function(err, user){
if(err){
res.json({"error": err});
return;
}
if(!user){
res.json({"message": "No user found"});
return;
}
if(user.password == password){
res.json(
{
"message": "User found",
"token": jwt.sign({"id": user.id}, opts.secretOrKey)
}
);
}
else{
res.json({"message": "Password did not match"});
}
});
});
app.post("/register", function(req, res){
new User({ email: req.body.email, password: req.body.password}).
save(function(err, user){
if(err){
res.json({"message": "User cannot be created"});
}
else{
res.json(
{
"message": "ok",
"token": jwt.sign({"id": user.id}, opts.secretOrKey)
}
);
}
});
});
app.get("/secret", passport.authenticate("jwt", {session: false}), function(req, res){
console.log(req.get('Authorization'));
res.json(req.user);
});
使用邮递员作为客户。从邮递员那里索取详细信息,
GET /secret HTTP/1.1
Host: localhost:3000
Content-Type: application/x-www-form-urlencoded
Authorization: JWT token_I_received_on_login
Cache-Control: no-cache
Postman-Token: 114060a3-3074-6688-6245-0b0cfe7e9f04
答案 0 :(得分:0)
知道了。在请求中犯了错误。
根据README,它应该是'授权' =' bearer token_received_on_login'
答案 1 :(得分:0)
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
应该是
ExtractJwt.fromAuthHeaderWithScheme('jwt');