我在节点应用程序中放置了一个JWT身份验证系统。
我使用拦截器将Bearer放在每个请求中。如果我在Angular中调用受限路径,或者如果我卷曲并在标题中指定令牌,它的效果很好 但是如果我直接在我的地址栏中输入限制路线,它就不起作用了。标题中没有Bearer,它不会通过拦截器。
这是我的拦截器(客户端):
angular.module('myApp).factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
});
angular.module('myApp').config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
这是我的限制路线(服务器端):
router.get('/restricted', expressJwt({secret: 'SecretStory'}), function(req, res) {
res.json({
name: 'You are allowed here !!'
});
})
如何在每个请求中将持有人添加到我的请求标头中,即使直接在地址栏中输入受限制的路由?
答案 0 :(得分:2)
当您直接在地址栏中输入网址时,您正在规避您的Angular代码,并且正如您所发现的那样,拦截器将无法运行。
你可以尝试detecting when the URL in the address bar changes并尝试解决问题,但我建议不要这样做。
相反,我会通过检测GET /restricted
Accept
text/html
标头application/json
(任何真正不是/restricted
的标头)来解决服务器端问题。然后使用包含Angular代码的HTML进行回复,并在页面加载时使用application/json
再次请求{{1}}。这是区分显式URL导航和Angular请求的好方法,并为您的API提供更好的超媒体支持。