AngularJS interceptor does not put JWT media in every request of node.js app

I have put JWT authentication system in node application.

I used an interceptor to put media on every request. It works well if I call the restricted route in Angular, or if I curl and specify the token in the header.
But if I entered the restricted route directly into the address bar, it doesn't work. There is no pointer 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 limited route (server side):

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

      

How do I make the transporter added to the request header on every request even when entering the restricted route directly into the address bar?

+3


source to share


1 answer


When you enter the url directly in the address bar, you bypass your Angular code and, as you found, the interceptor does not start.

You can try to detect when the url in the address bar changes and try to fix the problem, but I would recommend against that.



Instead, I would approach this problem on the server side by detecting a request GET /restricted

with a header Accept

text/html

(whatever 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 differentiate between explicit URL navigation and Angular requests and offer better hypermedia support for your API.

+2


source







All Articles