尝试在节点中实现 JWT 身份验证.在受保护的路线中获得未经授权

Trying to implement JWT authentication in node. Getting unauthorized in protected routes(尝试在节点中实现 JWT 身份验证.在受保护的路线中获得未经授权)
本文介绍了尝试在节点中实现 JWT 身份验证.在受保护的路线中获得未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试实现 JWT 身份验证./login 和/register 工作正常,它们返回身份验证令牌,但是当我尝试使用标头 'Authorization' = 'JWT token_received' 获取/secret 时,它返回一个字符串'unauthorized',我看不到来自 JWTStrategy 的日志记录.请让我知道我哪里出错了.

I am trying to implement JWT authentication. /login and /register work fine and they return authentication token, but when I try to GET /secret with a header 'Authorization' = 'JWT token_received', it returns a string 'unauthorized' and I can see no logging from JWTStrategy. Please let me know where I am going wrong.

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);
});

使用邮递员作为客户端.向邮递员索取详细信息,

Using postman as the client. Request details from postman,

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

推荐答案

知道了.请求中有错误.

Got it. Made a mistake in the request.

根据 README,应该是 'Authorization' = 'bearer token_received_on_login'

As per the README, it should be 'Authorization' = 'bearer token_received_on_login'

这篇关于尝试在节点中实现 JWT 身份验证.在受保护的路线中获得未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Using discord.js to detect image and respond(使用 discord.js 检测图像并响应)
Check if user ID exists in Discord server(检查 Discord 服务器中是否存在用户 ID)
Guild Member Add does not work (discordjs)(公会成员添加不起作用(discordjs))
Creating my first bot using REPLIT but always error Discord.JS(使用 REPLIT 创建我的第一个机器人,但总是错误 Discord.JS)
How do I code event/command handlers for my Discord.js bot?(如何为我的 Discord.js 机器人编写事件/命令处理程序?)
How to find a User ID from a Username in Discord.js?(如何从 Discord.js 中的用户名中查找用户 ID?)