AngularJS中的$ http Auth Headers

mwa*_*tys 40 http-headers angularjs

我有一个角度应用程序正在命中节点API.我们的后端开发人员已经在API上实现了基本身份验证,我需要在请求中发送auth标头.

我跟踪了:

$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
Run Code Online (Sandbox Code Playgroud)

我试过了:

.config(['$http', function($http) {
       $http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' +    password);
}])
Run Code Online (Sandbox Code Playgroud)

以及将其直接附加到请求:

$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})
Run Code Online (Sandbox Code Playgroud)

但没有任何作用.怎么解决这个?

Eli*_*lka 32

你正在混合使用案例; 实例化的services($http)不能在配置阶段使用,而提供程序不能在运行块中使用.从模块文档:

  • 配置块 - [...]只有提供者和常量可以注入配置块.这是为了防止在完全配置服务之前意外实例化服务.
  • 运行块 - [...]只有实例和常量可以注入运行块.这是为了防止在应用程序运行时进一步进行系统配置.

因此,请使用以下任一方法:

app.run(['$http', function($http) {
    $http.defaults.headers.common['Authorization'] = /* ... */;
}]);
Run Code Online (Sandbox Code Playgroud)
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = /* ... */;
}])
Run Code Online (Sandbox Code Playgroud)

  • 因为它是一个配置的东西,而你正在研究该服务的一个具体实例. (3认同)
  • 谢谢@EliranMalka非常有意义. (3认同)
  • 为什么我们不能在控制器级别编写`$ http.defaults.headers.common ['Authorization'] =/*...*/;` (2认同)
  • @natureminded谢谢,是的,我知道.我只是对风格方法感到好奇.使用方括号表示法允许使用任意属性值来定义要访问的属性,而点表示法仅针对特定的非动态定义属性.这个约定在JavaScript中的使用比在这个特定的实例中要广泛得多,但是我不确定在这里使用方括号是否还有其他一些特定的原因.我只需要澄清:)感谢您的帮助. (2认同)

Nit*_*mar 13

您可以在控制器中使用它:

.controller('Controller Name', ['$http', function($http) {
   $http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password;
}]);
Run Code Online (Sandbox Code Playgroud)

  • 应该在配置阶段完成,但它也需要在登录后完成,所以你可以在logincontroller中设置它 (2认同)

bri*_*her 13

我有一个服务工厂,它有一个角度请求拦截器,如下所示:

var module =  angular.module('MyAuthServices', ['ngResource']);

module
    .factory('MyAuth', function () {
    return {
        accessTokenId: null
    };
})    
.config(function ($httpProvider) {
    $httpProvider.interceptors.push('MyAuthRequestInterceptor');
})

.factory('MyAuthRequestInterceptor', [ '$q', '$location', 'MyAuth',
    function ($q, $location, MyAuth) {
        return {
            'request': function (config) {


                if (sessionStorage.getItem('accessToken')) {

                    console.log("token["+window.localStorage.getItem('accessToken')+"], config.headers: ", config.headers);
                    config.headers.authorization = sessionStorage.getItem('accessToken');
                }
                return config || $q.when(config);
            }
            ,
            responseError: function(rejection) {

                console.log("Found responseError: ", rejection);
                if (rejection.status == 401) {

                    console.log("Access denied (error 401), please login again");
                    //$location.nextAfterLogin = $location.path();
                    $location.path('/init/login');
                }
                return $q.reject(rejection);
            }
        }
    }]);
Run Code Online (Sandbox Code Playgroud)

然后在我的登录控制器中登录时,我使用以下行存储了accesstoken:

sessionStorage.setItem('currentUserId', $scope.loginResult.user.id);
sessionStorage.setItem('accessToken', $scope.loginResult.id);
sessionStorage.setItem('user', JSON.stringify($scope.loginResult.user));
sessionStorage.setItem('userRoles', JSON.stringify($scope.loginResult.roles));
Run Code Online (Sandbox Code Playgroud)

这样我可以在登录后的每个请求上为请求分配标题.这就是我这样做的方式,完全是批评,但它看起来效果很好.


MrZ*_*ime 6

angularjs文档中,您可以看到一些设置标题的方法,但我认为这就是您要搜索的内容:

$http({
    method: 'POST',
    url: '/theUrl',
    headers: {
        'Authorization': 'Bearer ' + 'token'
         //or
         //'Authorization': 'Basic ' + 'token'
    },
    data: someData
}).then(function successCallback(response) {
    $log.log("OK")
}, function errorCallback(response) {
    if(response.status = 401){ // If you have set 401
        $log.log("ohohoh")
    }
});
Run Code Online (Sandbox Code Playgroud)

我在我的angularjs客户端使用这个结构与ASP.NET 5服务器,它的工作原理.


Bet*_*aba 4

$http 文档中,您可以看到应该使用 $httpProvider 设置默认标头:

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = 'Basic auth';
}]);
Run Code Online (Sandbox Code Playgroud)