简体   繁体   English

如何在nodejs中验证JWT令牌

[英]How to verify JWT token in nodejs

In my case I want to validate if the user is logged in or not using JWT library and nodejs for my backend.在我的例子中,我想验证用户是否登录或不使用 JWT 库和 nodejs 作为我的后端。 In in code I cant validate the user if the user is logged in or not.在代码中,我无法验证用户是否登录。 it always says user not authenticated.它总是说用户未通过身份验证。

This is my validation function from my middleware这是我的中间件验证 function

const validateToken = (req, res, next) => {
    const accessToken = decode["jwtToken"];

    if(!accessToken) {
        return res.json({error: "User not authenticated"});
    }else{
        try{
            const validToken = verify(accessToken, "Secret");
    
            if(validToken){
                console.log("user authenticated");
                req.authenticated = true;
                return next;
            }
        }catch (err) {
            return res.json({error: err});
        }
    }
}

And this is the code that will automatically make a token and store it into my cookie这是将自动生成令牌并将其存储到我的 cookie 中的代码

const accessToken = createToken(user);

            res.cookie("jwtToken", accessToken, {
                maxAge: 60 * 60  * 12 * 1000, //12 hrs =======> 9sec  for testing 3 * 3 * 1000
                httpOnly: true,
            })

            res.json(accessToken);

Can someone can help me with my code?有人可以帮我处理我的代码吗?

I solve my problem Everyone:-) I just miss the next declaration I used return next;我解决了我的问题 每个人:-) 我只是错过了我接下来使用 return 的下一个声明; instead of return next();而不是 return next();

here is my code for my middleware这是我的中间件代码

const validateToken = (req, res, next) => {
    const accessToken = req.cookies["token"];

    if(accessToken) {
        try{
            const validToken = jwt.verify(accessToken, "bluedragon14S");
    
            if(validToken){
                console.log("user authenticated");
                req.authenticated = true;
                return next();
            }
        }catch (err) {
            return res.json({error: err});
        }
    }else{
        return res.json({error: "User not authenticated"});
    }
}

I hope it helps the other students has same error with me.我希望它能帮助其他学生与我有同样的错误。 Happy coding;-)编码愉快;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM