Where should I inject bearer tokens in $ http in AngularJS?

After the user credentials have been accepted, I get the media 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 these tokens be permanent throughout the session, or should I use a different technique?

[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 
+7
angularjs authentication oauth bearer-token
source share
1 answer

A great way to solve this problem is to create an authInterceptor factory responsible for adding a 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 application:

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

Now all requests made using $ http (or $ resource, for that matter) will be sent using the authorization header.

Doing this method instead of changing $ http.default means that you get more control over the request and response, and you can also use your own error handler or use any logic that you want to determine whether to send an authentication token or not.

+9
source

All Articles