繁体   English   中英

如何在客户端实现 JSON Web 令牌 - Node.js

[英]How to implement JSON web token in client side - Node.js

我正在开发一个 Node.js express 应用程序,使用JWT进行身份验证以访问我的管理页面。 我用 Postman 测试了我的路线,效果很好,问题出在客户端。 我将简化我的代码和我的问题,使问题非常清晰。

我的问题是如何在使用localStorage在本地存储令牌后重定向到我的管理页面?

我已经尝试用ajax解决这个问题,但页面还是一样。 我也试过window.location='/admin'但在这个我不能发送包含令牌的标头

首先我的服务器端:

app.get('/admin', verifyToken, function(req, res, next) {
    res.render('views/admin');
});

function verifyToken(req, res, next) {
    var token = req.headers['access-token'];
    if (!token)
      return res.status(401).send({ auth: false, message: 'NO TOKEN PROVIDED' });        

      jwt.verify(token, config.secret_key, function(err, decoded) {
      if (err)
      return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

      console.log("Token is valid");
      next();
    });
  }

客户端:

function login(event) {
            event.preventDefault();
            let formData = new FormData(event.target);

            fetch("/admin/login", {
                    method: 'POST',
                    body: formData 
            }).then(function (response) {          
                    return response.json();
                }).then(function (result) {
                    if (result.auth === true) {
                        localStorage.token = result.token;
                    //HERE IS THE PROBLEM
                       $.ajax({ 
                         type : "GET", 
                         url : "/admin", 
                         beforeSend: function(xhr){
                        xhr.setRequestHeader('access-token', localStorage.token);
                                    },
                success : function(result) { 
                         //HERE IS THE PROBLEM                
                       window.location='/admin';
                         }
                        }); 
                    } else {
                        console.log("Incorrect username or password.");
                    }
                });       
        }

那么我如何像我在客户端的 Postman 中所做的那样在标头中发送令牌并自动重定向,有什么方法吗? 非常感谢。

如果您的管理页面呈现为完整页面,则只需在 /admin ajax 请求成功处理程序中执行 document.write(result)

success : function(result) {                 
                   document.write(result)
                     }

我注意到使用这种方法不是一个好习惯。 在我的示例中,在客户端进行重定向并不好,在服务器端进行重定向会更好,而且我使用localStorage 的安全性较低的方法来存储我的令牌。

所以我告诉自己为什么不在我的服务器端进行重定向,为此我使用cookie-parser中间件来检查创建的 cookie 是否包含我的令牌,如果是真的,则重定向到管理页面。

Cookie 或 localStorage 都不安全,但 cookie 是存储我的令牌的不错选择,因为无论是使用 HTTP 还是 HTTPS, Web 存储在传输过程中都不会强制执行任何安全标准。

我的服务器端

app.get('/admin', verifyToken, function(req, res,next) {
    res.render('views/admin');
});

app.get('/admin/login', function(req, res){
      if(req.cookies.myToken)//Make redirection
   return res.redirect('/admin');
    res.render('views/login');
});

function verifyToken(req, res, next) {
    var token = req.cookies.myToken;
    if (!token)
      return res.status(401).send({ auth: false, message: 'No Token Provided!'});

      jwt.verify(token, config.secret_key, function(err, decoded) {
      if (err)
      return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
      req.userId = decoded.id;
      next();
    });
  }

客户端:

fetch("/admin/login", {
                    method: 'POST',
                    body: formData,
                    credentials: 'include',
            }).then(function (response) {
                    return response.json();
                }).then(function (result) {
                    console.log(result);
                    if (result.auth === true) {
                        window.location="/admin";                            
                    } else {
                       console.log("Incorrect username or password.");
                  }
                })

如果您使用 jwt,则每次请求都会发送令牌。

通常这将使用 jquery 或 angular 之类的框架来完成,您使用一个中间件将令牌添加到每个请求中。

这里是 jquery 的示例。

$.ajaxPrefilter(function( options ) {
    if (options.beforeSend) {
        options.beforeSend = function (xhr) {
            xhr.setRequestHeader('Authorization',   
                 'Bearer'+localStorage.getItem('token'));
        }
    }
});

如果你有,你可以使用你的代码:

function login(event) {
            event.preventDefault();
            let formData = new FormData(event.target);

            fetch("/admin/login", {
                    method: 'POST',
                    body: formData 
            }).then(function (response) {          
                    return response.json();
                }).then(function (result) {
                    if (result.auth === true) {
                        localStorage.token = result.token;
                        window.location='/admin';
                         }
                        }); 
                    } else {
                        console.log("Incorrect username or password.");
                    }
                });       
        }

暂无
暂无

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

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