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

Deadly 提交于 2019-12-08 17:20:56

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/25009634/where-should-i-inject-bearer-tokens-into-http-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!