Jean Reptile
Jean Reptile

Reputation: 107

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

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?

Upvotes: 4

Views: 1082

Answers (1)

Erik Gillespie
Erik Gillespie

Reputation: 3959

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.

Upvotes: 2

Related Questions