【问题标题】:How to check user token in Angular?如何在 Angular 中检查用户令牌?
【发布时间】:2017-02-23 20:14:17
【问题描述】:

我使用 node 和 angular 用 JWT 生成令牌,无法检查用户是否被授权。

节点:

module.exports.authenticate = function(req, res) {
    var user = new User(req.body);
    User.findOne({
        username: req.body.username
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
            res.json({ success: false, message: 'Authentication failed. User not found.' });
        }
        else if (user) {
            if (user.password != req.body.password) {
                res.json({ success: false, message: 'Authentication failed. Wrong password.' });
            }
            else {
                var token = jwt.sign(user, config.secret, {
                    expiresIn: 60*60*24
                });

                res.json({
                    success: true,
                    token: token
                });
            }
        }
    });
};

角度:

$http(req)
            .then(function (response) {
                console.log(response.data.success);
                if(response.data.success) {
                    var user = localStorage.setItem('token', JSON.stringify(response.data));
                    token = localStorage.getItem('token');
                    // console.log('User info: ', JSON.parse(getuser));
                    // window.location = "/dashboard";
                    return response.data;
                }
            }, function (response) {

            }
        );
    }

更改路线时如何查看token?

一般来说,我该如何使用 Token?

【问题讨论】:

    标签: angularjs node.js express jwt angularjs-http


    【解决方案1】:

    Angular ui-router 在您更改路由时提供$routeChangeStart 事件。您可以通过以下方式使用它。

    $rootScope.$on('$routeChangeStart', function (event, next, current){
       //you can code here something to be run on changing routes
    }
    

    您可能想查看here 以获取详细的事件文档。

    关于更通用的实现,您可以创建一个服务来在登录时或获得它时保留您的令牌。此后,您可以继续从服务中获取令牌以供将来进行任何比较。

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2020-06-30
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2012-10-03
      • 2015-11-22
      • 2021-07-31
      • 2022-10-20
      相关资源
      最近更新 更多