【问题标题】:Correct way to protect URL with JSON web token and node.js/express使用 JSON Web 令牌和 node.js/express 保护 URL 的正确方法
【发布时间】:2015-10-27 14:56:41
【问题描述】:

我目前正在使用 node.js 授权用户使用 JSON Web 令牌,并使用 EJS 作为视图引擎进行表达。

在我的 server.js 文件中使用简单的中间件:

app.use(function(request, response, next){
        var token = request.body.token || request.query.token || request.headers['x-access-token'];
        console.log(request.body);
        if(token){
        jwt.verify(token, app.get('superSecret'), function(err, decoded){
                   if(err){
                   response.json({"message": "Failed to authenticate user"});
                   }
                   else{
                   request.decoded = decoded;
                   next();
                   }
                   });
        }
        else{
        return response.status(403).json({"message":"No token was provided"});
        }
        });

以及它下面的受保护路线,例如:

app.post('/userlist', function(request, response) {
        response.json({some: json})
        });

我无法理解或弄清楚如何保护 GET 路由,例如:

app.get('/userprofile', function(request, response) {
            response.render('pages/userprofile');
            });

如果我通过某个 url 直接发出请求 www.example.com/userprofile 访问被拒绝,因为请求中没有包含令牌。

如果我通过 ajax 实现:

$.ajax({
           type:"GET",
           url:"https://www.example.com/userprofile",
           headers:{"x-access-token": token },
           success: function(result, success){
           },
           error: function (result, error){
           }
       });

响应没有被渲染,而是在结果对象中返回。我的电线在这里某处交叉。

【问题讨论】:

    标签: javascript json node.js authentication


    【解决方案1】:

    需要传递令牌才能使用。如果服务器无权访问它,则服务器无法验证它。因此,您可以在路径中传递令牌:

    app.get('/userprofile/:token',function(request,response){
      console.log(request.params.token);
    });
    

    在查询字符串中:

    app.get('/userprofile',function(request,response){
      console.log(request.query.token);
    });
    

    或作为 cookie:

    var cookieParser = require('cookie-parser');
    app.use(cookieParser);
    app.get('/userprofile',function(request,response){
      console.log(request.cookies.token);
    });
    

    【讨论】:

    • 当我在本地存储中有令牌时,我很困惑如何做到这一点。如果它是标头中的简单链接,我如何将此值附加到请求中,即<li><a href="/userprofile">Profile</a></li>
    • 听起来 cookie 将成为您的最佳选择。您是否考虑过使用 express-session?
    • 回到这一点,使用上面的令牌方法是不是“不好的做法”,只是附加到 url?
    • 我会研究 express-session
    【解决方案2】:

    应该发送http响应代码,默认为200,如您的response.json({"message": "Failed to authenticate user"});

    试试 response.json(401, {"message": "Failed to authenticate user"});

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 2018-05-13
      • 2020-12-05
      • 2019-11-13
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 2021-10-02
      相关资源
      最近更新 更多