AngularJS interceptor not putting JWT Bearer in every request of node.js app

自古美人都是妖i 提交于 2019-12-12 13:11:20

问题


I put a JWT authentication system in a node app.

I used an interceptor to put the Bearer in every request. It works well if I call a restricted route within Angular or if I curl and specify the token in the header.
But if I enter the restricted route directly in my address bar, it doesn't work. There is no Bearer in the header, it doesn't go through the interceptor.

Here is my interceptor (client-side):

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');
});

Here is my restricted route (server-side):

router.get('/restricted', expressJwt({secret: 'SecretStory'}), function(req, res) {
  res.json({
      name: 'You are allowed here !!'
    });
})

How to make the bearer to be added to my request header on every request, even in typing the restricted route directly into the address bar?


回答1:


When you enter a URL directly in the address bar you are circumventing your Angular code and, as you've discovered, the interceptor will not run.

You could try detecting when the URL in the address bar changes and try to work around the problem, but I would recommend against this.

Instead, I would approach this problem server-side by detecting a GET /restricted request with an Accept header of text/html (anything that is not application/json really). Then respond with HTML that includes your Angular code and request /restricted again using application/json when the page loads. This would be a good way to distinguish between explicit URL navigation and Angular requests and offers better hypermedia support to your API.



来源:https://stackoverflow.com/questions/29774068/angularjs-interceptor-not-putting-jwt-bearer-in-every-request-of-node-js-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!