Where should I inject Bearer tokens into $http in AngularJS?

martins picture martins · Jul 29, 2014 · Viewed 9.6k times · Source

After the user's credential has been accepted I fetch the Bearer token [1] and update the default headers:

     $http.defaults.headers.common.Authorization = "Bearer #{data.access_token}"

This is done at the end of the $scope.signIn() method. Will the tokens be persistent throughout the entire session or should I use an other technic?

[1] https://github.com/doorkeeper-gem/doorkeeper/wiki/Client-Credentials-flow

app.run run = ($http, session) ->
    token = session.get('token')
    $http.defaults.headers.common['Authorization'] = token

Answer

mz3 picture mz3 · May 11, 2015

A great way to solve this problem is to create an authInterceptor factory responsible for adding the header to all $http requests:

angular.module("your-app").factory('authInterceptor', [
  "$q", "$window", "$location", "session", function($q, $window, $location, session) {
    return {
      request: function(config) {
        config.headers = config.headers || {};
        config.headers.Authorization = 'Bearer ' + session.get('token'); // add your token from your service or whatever
        return config;
      },
      response: function(response) {
        return response || $q.when(response);
      },
      responseError: function(rejection) {
        // your error handler
      }
    };
  }
]);

Then in your app.run:

// send auth token with requests
$httpProvider.interceptors.push('authInterceptor');

Now all requests made with $http (or $resource for that matter) will send along the authorization header.

Doing it this way instead of changing $http.defaults means you get way more control over the request and response, plus you can use a custom error handler too or use whatever logic you want to determine whether the auth token should be sent or not.