Add Authorization header to AngularJS $http

I recently had to add an Authorization header to all $http requests in an AngularJS app.

Here’s how I did it in Coffeescript.

#AuthData.coffee

angular.module('app')
.factory 'AuthDataService', [
  'localStorageService'
  '$base64'
  '$http'
  (localStorageService, $base64, $http) ->
    current_auth_data = localStorageService.get('authorization_token')
    if current_auth_data
      $http.defaults.headers.common['Authorization'] = "Basic #{current_auth_data}"

    return {
      setAuthData: (authdata) ->
        return unless authdata
        encoded = $base64.encode(authdata)
        localStorageService.set('authorization_token', encoded)
        $http.defaults.headers.common['Authorization'] = "Basic #{encoded}"
      clearAuthData: ->
        localStorageService.remove('authorization_token')
        $http.defaults.headers.common['Authorization'] = ''
      getAuthData: ->
        return localStorageService.get('authorization_token')
    }
]

Upon initialization it checks if there’s a authorization_token saved in your local storage. If there is, set it as a Authorization header on $http.

Whenever you set or clear the auth data, the header for $http changes as well.

EDIT: I’ve written another post about how to add Authorization header to AngularJS $http