Angular Node – 在打开新的浏览器窗口时向服务器发送令牌

这个问题是不言自明的:我有一个令牌存储在我的浏览器。 当我login时,服务器端authentication中间件使用Passport来authentication我。 但是,当我closures并重新打开浏览器窗口时,令牌仍然存在,但护照不知道我是谁。

我怎样才能从客户端到服务器端检索令牌?

以下是我的代码。

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度应用程序,并附加您的身份validation令牌以及您发送到服务器的每个请求。

有关请求拦截器的更多信息,请访问: https : //docs.angularjs.org/api/ng/service/$http

所以我的问题的答案是做一个请求拦截器,我在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)初次login时的Passport.authentication ,或b)随后在自定义函数checkAuthentication()检查令牌validation。

 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不解码“JWT格式错误” – 节点angular