$http AngularJS中的身份验证标头



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

我已经追踪到:

$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);

我试过:

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

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

$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})

但没有任何效果。如何解决这个问题?

您正在混合用例; 实例化服务 ( $http ) 不能在配置阶段使用,而提供程序不会在运行块中工作。从模块文档中:

  • 配置块 - [...] 只能注入提供程序和常量 到配置块中。这是为了防止意外实例化 在完全配置服务之前。
  • 运行块 - [...] 只能将实例和常量注入到运行中 块。这是为了防止在 应用程序运行时。

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

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

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

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);
            }
        }
    }]);

然后在登录我的登录控制器时,我使用以下行存储访问令牌:

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));

这样,我可以在登录后发出的每个请求上为请求分配标头。 这就是我的做法,完全可以批评,但它似乎效果很好。

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

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

在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")
    }
});

我在我的 angularjs 客户端中使用这种结构,带有 ASP.NET 5 服务器并且可以工作。

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

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

工作示例:我从@MrZime那里学到了这一点 - 谢谢!并阅读 https://docs.angularjs.org/api/ng/service/$http#setting-http-headers

截至 2018 年 3 月 2 日的最新 NGULARJS v1.6.x

        var req = {
            method: 'POST',
            url: 'https://api.losant.com/applications/43fdsf5dfa5fcfe832ree/data/last-value-query',
            headers: {
                'Authorization': 'Bearer ' + 'adsadsdsdYXBpVG9rZW4iLCJzrdfiaWF0IjoxNdfsereOiJZ2V0c3RfdLmlvInfdfeweweFQI-dfdffwewdf34ee0',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            data: {
                "deviceIds": [
                    "a6fdgdfd5dfqaadsdd5",
                    "azcxd7d0ghghghghd832"
                ],
                "attribute": "humidity"
            }
        }


        $http(req).then(function successCallback(response) {
            $log.log("OK!")
             returnedData = response.data
        }, function errorCallback(response) {
            if (response.status = 401) { // If you have set 401
                $log.log("BAD 401")
            }
            else {
                $log.log("broken at last")
            }
        });

将其添加到您的.js文件中,并将其包含在您的.js文件中.html并在 chrome 上的 debug/F12 中查看控制台面板,您应该获得确定状态,"返回数据"是您想要的最终。享受数据!

在将

用户:密码附加到"基本"之前,请尝试对用户:密码进行base64编码,如下所示:

headers: {
  'Authorization': "Basic " + auth64EncodedUserColonPass
}

aap.run方法中添加以下行

$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';

最新更新