【问题标题】:How to pass JsonWebToken x-access-token through angular js如何通过 Angular js 传递 JsonWebToken x-access-token
【发布时间】:2016-08-21 13:27:12
【问题描述】:

我使用 jsonwebtoken 作为身份验证方法创建了一个 node express RESTful API。但无法使用 Angular js 将 x-access-token 作为标头传递。

我的 JWT 令牌认证脚本是,

apps.post('/authenticate', function(req, res) {

    // find the item
    Item.findOne({
        name: req.body.name
    }, function(err, item) {

        if (err) throw err;

        if (!item) 
        {
            res.json({ success: false, message: 'Authentication failed. item not found.' });
        } 
        else if (item) 
        {

            // check if password matches
            if (item.password != req.body.password) 
            {
                res.json({ success: false, message: 'Authentication failed. Wrong password.' });
            } 
            else 
            {

                // if item is found and password is right
                // create a token
                var token = jwt.sign(item, app.get('superSecret'), {
                    expiresIn: 86400 // expires in 24 hours
                });



                    res.json({
                        success: true,
                        message: 'Enjoy your token!',
                        token: token
                    }); 





            }       

        }

    });
});

检查令牌是否正确的中间件是,

apps.use(function(req, res, next) {

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.params.token || req.headers['x-access-token'];

    // decode token
    if (token) 
    {

        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {          
            if (err) 
            {
                return res.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.'
        });

    }

});

最后是GET方法脚本,

app.get('/display', function(req, res) {
    Item.find({}, function(err, items) {



            $http.defaults.headers.common['X-Access-Token']=token;

            res.json(items);
});
});

但它总是无法通过身份验证。请任何人帮我解决这个问题。我真的被困在这里了。

它始终只显示以下身份验证失败消息。

{"success":false,"message":"No token provided."}

【问题讨论】:

  • 你之前搜索过吗,你得到了什么?
  • @jicks 你能展示你的角度路线吗?

标签: angularjs node.js json-web-token


【解决方案1】:

如果您使用 $http 作为角度控制器中的依赖项,那么我猜这会对您有所帮助 -

var token = this.AuthToken.getToken();
$http.get('/api/me', { headers: {'x-access-token': token} });

您上传 Angular 代码后,我会根据您的代码更改此设置。

【讨论】:

  • 但它不是完全角码。为了将 x-access-token 作为标头传递,我在节点 js 中使用了 angular js 脚本。
  • 您可以阅读这篇文章 - using-json-web-tokens-node-js。我认为它会帮助您获得有关您正在寻找的东西的一些信息。
  • 我仍然不知道如何传递标题。@Sk Arif
【解决方案2】:

客户端应该使用 Bearer 方案在 Authorization 标头中发送令牌,因为自 2012 年以来已弃用“X-”标头:

你的节点现在应该是:

apps.post('/authenticate', function(req, res) { 
    .....
    var token = 'Bearer' + ' ' + jwt.sign(item, app.get('superSecret'), {
        expiresIn: 86400 // expires in 24 hours
    });
    .....
 }

apps.use(function(req, res, next) {
    // Trim out the bearer text using substring
    var token = req.get('Authorization').substring(7);
    ....
}

那么你的角码会变成:

var token = this.AuthToken.getToken();
$http.get('/api/me', { headers: {'Authorization': token} });

【讨论】:

  • 并非所有英雄都穿着斗篷,但这是前进的新方式吗?
【解决方案3】:

您可以创建一个拦截器来捕获所有 ajax 调用并将令牌注入标头。这样您就不会在每次进行 ajax 调用时都注入它。

如果您想走这条路,这是一个很好的起点: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2019-04-23
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2019-07-11
    • 2016-06-19
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多