[英]$http Auth Headers in AngularJS
I have an angular application that is hitting a node API. 我有一个角度应用程序正在命中节点API。 Our backend developer has implemented basic auth on the API, and I need to send an auth header in my request.
我们的后端开发人员已经在API上实现了基本身份验证,我需要在请求中发送auth标头。
I've tracked down: 我跟踪了:
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
I've tried: 我试过了:
.config(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
}])
As well as appending it directly to the request: 以及将其直接附加到请求:
$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})
But nothing works. 但没有任何作用。 How to solve this?
怎么解决这个?
You're mixing the use cases; 你正在混合使用案例; instantiated services (
$http
) cannot be used in the config phase, while providers won't work in run blocks. 实例化服务(
$http
)不能在配置阶段使用,而提供程序不能在运行块中使用。 From the module docs : 从模块文档 :
- Configuration blocks - […] Only providers and constants can be injected into configuration blocks.
配置块 - [...]只有提供者和常量可以注入配置块。 This is to prevent accidental instantiation of services before they have been fully configured.
这是为了防止在完全配置服务之前意外实例化服务。
- Run blocks - […] Only instances and constants can be injected into run blocks.
运行块 - [...]只有实例和常量可以注入运行块。 This is to prevent further system configuration during application run time.
这是为了防止在应用程序运行时进一步进行系统配置。
So use either of the following: 因此,请使用以下任一方法:
app.run(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = /* ... */;
}]);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = /* ... */;
}])
You can use it in the controller: 您可以在控制器中使用它:
.controller('Controller Name', ['$http', function($http) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password;
}]);
I have a service factory that has an angular request interceptor like so: 我有一个服务工厂,它有一个角度请求拦截器,如下所示:
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);
}
}
}]);
Then on logging in in my login controller I store the accesstoken using this line: 然后在我的登录控制器中登录时,我使用以下行存储了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));
This way I can assign the headers to the request on every request made after I log in. This is just the way I do it, and is totally up for criticism, but it appears to work very well. 这样我可以在登录后的每个请求上为请求分配标题。这就是我这样做的方式,完全是批评,但它看起来效果很好。
In the angularjs documentation you can see some ways to set headers but I think this is what you are searching: 在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")
}
});
I'm using this structure in my angularjs client with an ASP.NET 5 server and it works. 我在我的angularjs客户端使用这个结构与ASP.NET 5服务器,它的工作原理。
In the $http doc you can see that you should set the default headers using $httpProvider: 在$ http文档中,您可以看到应使用$ httpProvider设置默认标头:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Basic auth';
}]);
WORKING EXAMPLE: I have learnt this from @MrZime - Thanks! 工作示例:我从@MrZime学到了这一点 - 谢谢! and Read https://docs.angularjs.org/api/ng/service/ $http#setting-http-headers
并阅读https://docs.angularjs.org/api/ng/service/ $ http#setting-http-headers
Latest v1.6.x of NGULARJS as of 2018 MARCH 2nd 最新的NGULARJS v1.6.x截至2018年3月2日
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")
}
});
Add it to your.js file and include this your.js in your.html file and look at console panel in debug/F12 on chrome you should get OK status and "returnedData" is what you want in the end. 将它添加到your.js文件中并将此your.js包含在your.html文件中,并在chrome / F12上查看控制台面板上的chrome,你应该得到OK状态,“returnData”最终是你想要的。 Enjoy the data!
享受数据!
Try base64 encoding your user:password before you append it to "Basic", as in: 在将其附加到“Basic”之前,请尝试使用base64编码您的用户:密码,如下所示:
headers: {
'Authorization': "Basic " + auth64EncodedUserColonPass
}
在aap.run
方法中添加以下行
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.