我正在尝试向access发送的所有http请求(用于访问REST服务器的$resource)添加一个头,以添加基本的Auth信息(来自用户输入的用户名/密码)。
我认为当用户点击登录按钮时,它就像$http.defaults.headers.common['Authorization'] = value;一样简单(其中值是正确格式化的auth信息),但是当请求被发送时,会返回403个未经授权的请求,并检查Chrome的网络选项卡中的请求,不会在简单的资源查询上设置标题。
我已经搜索了很长一段时间了,有几个问题提到了CORS是问题所在(事实并非如此,我在服务器端设置了正确的标题,并且还尝试使用chrome关闭web安全运行,以反复检查这是否有干扰)。其他答案建议使用拦截器,但在我看来,对于如此简单的任务(虽然这是我想我必须使用的唯一方法),这似乎是过度设计的。
编辑:其他信息:我确信CORS不是问题,因为不需要身份验证的服务器请求成功并返回预期的响应。这是授权头设置不正确(或根本不正确)的问题。
发布于 2015-07-24 12:49:35
最佳实践是创建一个Http请求拦截器,并在那里添加授权头。
angular.module("MyApp").factory("authHttpRequestInterceptor", ["authenticationDataService",
function (authenticationDataService) {
return {
request: function (config) {
// This is the authentication service that I use.
// I store the bearer token in the local storage and retrieve it when needed.
// You can use your own implementation for this
var authData = authenticationDataService.getAuthData();
if (authData && authData.accessToken) {
config.headers["Authorization"] = 'Bearer'+ authData.accessToken;
}
return config;
}
};
}]);之后,在主模块中注册拦截器:
angular.module("MyApp").config([
"$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push('authHttpRequestInterceptor');
}]);发布于 2015-07-24 22:29:35
您可以使用transformRequest.maybe,您可以使用$httpProvider.interceptors,您可以使用$resource,尝试使用它的属性,它可以帮助您。
https://stackoverflow.com/questions/31608486
复制相似问题