1

i'm using asp.net webapi. Authentication is basic authentication by Thinktecture library.

When the user logs in, the username and password is stored in a session cookie using $CookieStore.

i'm adding the credentials to the header for every get request as below

$http.defaults.headers.common['Authorization'] = 'Basic '+$cookieStore.get('__RequestVerificationToken');

The problem is, i have to call this before every get request. Is there a way that the Angular will automatically add this to the header and when the response is 401, then the user should automatically redirect to login page.

4

1 回答 1

0

您是否尝试过使用 config 设置站点范围内的 http 标头?:

var app = angular.module('myApp', []);
app.config(['$httpProvider', function($httpProvider, $cookieStore) {
  $httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('__RequestVerificationToken');
}]);

请注意,在我的示例中,我专门将默认 Authorization 标头仅添加到GET请求中。


关于问题的第二部分,您需要定义一个响应拦截器,它将捕获每个 http 响应,侦听 401 的状态代码并在它发生时广播一个适当的事件(或直接重定向到登录页面):

var app = angular.module('myApp', []);
app.config(['$httpProvider', '$location', function($httpProvider, $location){

    var interceptor = ['$rootScope', '$q', function($rootScope, $q) {
      var broadcasted;

        function success(response) {
        return response;
      }

      function error(response) {
        if (response.status === 401) {
          $rootScope.$broadcast('loginRequired');
          // or $location.url('/login');
          var deferred = $q.defer();
          return deferred.promise;
        }
        // otherwise
        return $q.reject(response);
      }

      return function(promise) {
        return promise.then(success, error);
      };

    }];

    $httpProvider.responseInterceptors.push(interceptor);
}]);
于 2013-06-15T18:45:40.577 回答