【问题标题】:Once I have generated a JSON Web Token how do I use it? (Node.js)生成 JSON Web 令牌后,如何使用它? (Node.js)
【发布时间】:2016-09-07 17:40:40
【问题描述】:

我正在使用 Node.js + Express 构建一个应用程序,并且我正在尝试使用 JSON Web 令牌进行身份验证。现在,一旦输入了有效的用户名/密码,服务器就会通过向客户端发送 JWT 来响应。

这是我迷路的地方。

如何将该令牌连同进一步的请求一起发送到服务器?

如何将其作为标头发送?

【问题讨论】:

  • 您是使用 Angular 还是 jQuery 来向服务器发送请求。
  • 感谢您这么快回复我。我正在使用 jQuery。

标签: node.js express jwt


【解决方案1】:

如何将该令牌连同进一步的请求一起发送到服务器?

  1. 您可以在您的请求 URL 中附加查询参数。 例如:

http://localhost:8080/api/users?token=tokenValue

  1. 您可以将其保存在 cookie 中,当您请求 URL 时,它将获取包含您的令牌的 cookie。使用document.cookie 将令牌保存在您的 cookie 中

如何将其作为标头发送?

使用 JQuery

$.ajax({
    type:"POST",
    beforeSend: function (request)
    {
        request.setRequestHeader("Authority", authorizationToken);
    },
    url: "entities",
    data: "",
    success: function(msg) {
    }
});

在服务器端,您可以:

var token = req.body.token || req.query.token || req.headers['x-access-token'];

对于 Cookie 解析,可以使用:Cookie-Parser

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

进一步阅读: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

【讨论】:

    【解决方案2】:

    client 可以将访问令牌设置为标头或查询参数或在请求正文中。以下是通过 header 发送的一种方式:

    $.ajax({
        url: 'foo/bar',
        headers: { 'x-access-token': 'some value' },
        data: {}
    }).done(function(result){
       //do something
    });
    

    最佳做法是将访问令牌保存在浏览器本地存储中,而不是保存在 cookie 中。一旦您获得令牌,一旦登录。

    服务器,在需要令牌的所有安全路由之上包含身份验证中间件的最佳方式。

    auth.middleware:

    'use strict';
    
    module.exports = function(req,res,next){
        const jwt = require('jsonwebtoken');
        const config = require('../config/config');
    
        // check header or url parameters or post parameters for token
        var token = req.body.token || req.query.token || req.headers['x-access-token'];
    
        // decode token
        if (token) {
    
            // verifies secret and checks exp
            jwt.verify(token, config.secret, function(err, decoded) {           
                if (err) {
                    return res.status(401).json({ success: false, message: 'Failed to authenticate token.' });      
                } else {
                    // if everything is good, save to request for use in other routes
                    req.decoded = decoded;  
                    next();
                }
            });
    
        } else {
    
            // if there is no token
            // return an error
            return res.status(403).send({ 
                success: false, 
                message: 'No token provided.'
            });
    
        }
    
    };
    

    路线

    //no token required
    app.post('/signup',users.create);
    
    app.post('/login',users.authenticate);
    
    const auth = require('../middleware/auth.middleware');
    //token required for below routes
    app.use(auth);    
    app.get('/info',index.getInfo);
    

    【讨论】:

      【解决方案3】:

      首先你需要在客户端使用http cookie (res.cookie("token","yourtoken")) 或者使用session 来设置json token

      当用户发送请求时,您需要将令牌发送到服务器。您可以使用 req.cookie.token 读取 cookie 并在中间件中验证它或使用会话

      【讨论】:

        猜你喜欢
        • 2015-07-20
        • 2020-02-03
        • 1970-01-01
        • 2016-03-14
        • 2018-05-24
        • 2018-02-02
        • 2018-08-02
        • 2017-10-06
        • 2019-01-14
        相关资源
        最近更新 更多