【问题标题】:Angular Node - send token to server upon opening new browser windowAngular Node - 在打开新的浏览器窗口时向服务器发送令牌
【发布时间】:2016-05-23 03:33:48
【问题描述】:

这个问题不言自明:我的浏览器上存储了一个令牌。当我登录时,服务器端身份验证中间件使用 Passport 对我进行身份验证。但是,当我关闭并重新打开浏览器窗口时,令牌仍然存在,但 Passport 不知道我是谁。

如何将令牌从客户端检索到服务器端?

下面是我的代码。

app.get('/main', ensureAuthenticated, function(req, res, next) {
    // thingToSend gets sent the first time, I will modify it
    // later so it doesn't resend token if token exists
    var thingToSend = {
        token: createSendToken(req.user, config.secret),
        id: req.user._id,
        username: req.user.username,
        authorization: req.user.authorization
    };      
    res.render('main.ejs', thingToSend);
});

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/login_page');
    }
}

【问题讨论】:

    标签: angularjs node.js token passport.js jwt


    【解决方案1】:

    所以我的问题的答案是制作一个我在 app.config 中注入的请求拦截器。请求拦截器收集令牌,并且在我的初始会话之后的任何时候,请求拦截器都会将令牌附加到请求标头:

    app.factory('httpInterceptor', function($q, $store, $window) {
    return {
        request: function (config){
            config.headers = config.headers || {};
            if($store.get('token')){
                var token = config.headers.Authorization = 'Bearer ' + $store.get('token');
            }
            return config;
        },
        responseError: function(response){
            if(response.status === 401 || response.status === 403) {
                $window.location.href = "http://localhost:3000/login";
            }
            return $q.reject(response);
        }
    };
    });
    

    然后它使用函数 ensureAuthentication() 来检查 a) Passport.authentication 在初始登录时,或 b) 此后随时在自定义函数 checkAuthentication() 中检查令牌身份验证。

    function ensureAuthenticated(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            var x = checkAuthentication(req, res, next);
            if (x === true) {
                return next();
            } else {
                res.redirect('/login_Page');
            }
        }
    }
    

    任何有兴趣查看checkAuthentication() 或我在解决有关 JSON Web 令牌的相关问题方面的进展的人:JWT not decoding "JWT malformed" - Node Angular

    【讨论】:

      【解决方案2】:

      您应该向您的 Angular 应用程序添加一个请求拦截器,并将您的身份验证令牌与您发送到服务器的每个请求一起附加。

      在此处阅读有关请求拦截器的更多信息:https://docs.angularjs.org/api/ng/service/$http

      【讨论】:

      • 几个小时前就想出来了,我正在研究一个函数。如果您有兴趣查看它,我会在找到修复程序时发布该功能。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多