简体   繁体   English

如何在Node.js应用程序中的客户端站点上处理JWT令牌?

[英]How to handle JWT token on the client site in Node.js application?

I am implementing JWT tokens for authentication. 我正在实现JWT令牌以进行身份​​验证。

I am not using any client-site framework like Angular or React. 我没有使用像Angular或React这样的客户端站点框架。 It is just EJS. 这只是EJS。

Step 1. I have an API developed that on successful login returns the token as shown on the picture below(I am using Postman for testing API): 步骤1.我开发了一个API,成功登录后返回令牌,如下图所示(我使用Postman测试API):

API response with JSON 使用JSON的API响应

Step 2. I am then accessing the restricted route and passing along the Authorization header with token value, by inputing it manually in the Postman and it works just fine. 步骤2.然后我访问受限制的路由,并通过令牌值传递Authorization标头,通过在Postman中手动输入它,它工作得很好。

My question is WHERE and HOW do I save the returned token from the step 1 on the client, so that it is sent in the header on step 2. 我的问题是WHERE以及如何从客户端上的步骤1保存返回的令牌,以便在步骤2的头中发送它。

I am novice to web-development and following the tutorials, but all the tutorials I found about implementing the JWT token are written for Angular or React when it comes to the client site. 我是web开发的新手并且遵循教程,但是我发现的关于实现JWT令牌的所有教程都是针对Angular或React编写的,当涉及到客户端站点时。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thank you! 谢谢!

First you must create the token with JWT : 首先,您必须使用JWT创建令牌:

const token=jwt.sign({
                userId: user._id
                },config.secret, {expiresIn: '24h'});
                res.json({success:true,message:'Success', token:token, user: {username:user.username}});

Then in your front youcan save it into the localStorage 然后在你的前面你可以将它保存到localStorage

This will generate a unique key that you can implement in your header 这将生成一个您可以在标头中实现的唯一键

After that in your routes when you want to check if there's a JWT in the header just make : 之后,在您的路由时要检查是否有在报头是一个JWT只是做:

router.use((req,res,next)=>{
        const token=req.headers['authorization'];
        if(!token){
            res.json({success:false, message:"No token provided"});
        }
        else{
            jwt.verify(token, config.secret, (err,decoded)=>{
                if(err){
                    res.json({success:false,message:"Token invalid: " + err});
                }
                else{
                    req.decoded=decoded;
                    next();
                }
            });
        }
    });

This is a middleware that will check if there's a JWT key in "authorization" header 这是一个中间件,它将检查“授权”标题中是否有JWT密钥

Note that every route coming after this one are going to run this middleware. 请注意,在此之后的每条路线都将运行此中间件。

Here You 'll find every details about JSON Web Tokens 在这里,您将找到有关JSON Web Tokens的所有详细信息

EDIT 编辑

Here's how you could do with an AJAX request: 以下是您如何处理AJAX请求:

$("submit").click(function(){

    $.ajax({
       url : 'api/login,',
       type : 'POST',
       data : {login: $('#login').val(),password:$('#password').val()}
       dataType : 'JSON',
       success : function(data, statut){
           localStorage.setItem('token',data.token) // assuming you send a json token
       },

       error : function(resultat, statut, erreur){
         // whatever code you want
       },

       complete : function(resultat, statut){

       }

    });

});

Have an object where you store the token, if you want to keep the token after the user leaves so that he will remain connected as long as the token is valid, you can save it in the localStorage. 有一个存储令牌的对象,如果你想在用户离开后保留令牌,这样只要令牌有效就会保持连接,你可以将它保存在localStorage中。

And when doing AJAX requests on client side, retrieve the token from your object of from localStorage and set the token in the Authorization header. 在客户端执行AJAX请求时,从localStorage的对象中检索令牌,并在Authorization标头中设置令牌。

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

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