Search code examples
ajaxangularjshttpangular-http-interceptors

AngularJS simple auth interceptor


I want to pass in the headers my token each time i make a request. the way i do it now is using:

$http.defaults.headers.common['auth_token'] =  $localStorage.token;

How could i do that to make that sent to every request, and when it throws an error it should do a

$state.go('login')

Solution

  • If you want to add your token to each request, and respond to any errors, your best bet would be to use an Angular HTTP interceptor.

    Subject to your needs, it might look something like this:

    $httpProvider.interceptors.push(function ($q, $state, $localStorage) {
      return {
    
        // Add an interceptor for requests.
        'request': function (config) {
          config.headers = config.headers || {}; // Default to an empty object if no headers are set.
    
          // Set the header if the token is stored.
          if($localStorage.token) {
            config.headers.common['auth_token'] = $localStorage.token;
          }
    
          return config;
        },
    
        // Add an interceptor for any responses that error.
        'responseError': function(response) {
    
          // Check if the error is auth-related.
          if(response.status === 401 || response.status === 403) {
            $state.go('login');
          }
    
          return $q.reject(response);
        }
    
      };
    });
    

    Hope this helps.