Angular 节点 - 打开新浏览器时向服务器发送令牌 window

Angular Node - send token to server upon opening new browser window

这个问题不言自明:我的浏览器上存储了一个令牌。当我登录时,服务器端身份验证中间件使用 Passport 对我进行身份验证。但是,当我关闭并重新打开浏览器时 window 令牌仍然存在,但 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');
    }
}

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

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

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

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().[=17 之后随时检查令牌身份验证=]

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 网络令牌的相关问题方面取得进展的人:JWT not decoding "JWT malformed" - Node Angular