使用的服务器是 Apache,它配置为基本身份验证
<LocationMatch "^/login/(.*)$">
AllowMethods POST OPTIONS
<LimitExcept OPTIONS>
Require valid-user
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "authorization,content-type"
Header always set Access-Control-Allow-Method "POST,OPTIONS"
</LimitExcept>
AuthType basic
AuthName "Authentication Required"
AuthBasicProvider file
AuthUserFile "/etc/sec/.secret-file"
LogLevel debug
Require valid-user
ErrorDocument 401 "Authorization Failure"
RequestHeader set X-Authenticated-User %{REMOTE_USER}s
ProxyPass "http://127.0.0.1:8080/$1"
</LocationMatch>
Angular 2 代码如下 -
public login = (resrc: string, item: any): Observable<any> => {
this.headers.append('Authorization', 'Basic ' + btoa(item['userName']+':'+item['password']));
let options = new RequestOptions({ headers: this.headers, withCredentials: true });
return this._http.post(this.serverUrl+"login/"+this.apiUrl+resrc,{}, options)
.timeoutWith(5000, Observable.throw(new Error('Request timed out.')))
.map((response: Response) => { return response; })
.catch(this.handleError);
}
请求 header PDU -
OPTIONS /login/api/system/sessions/ HTTP/1.1
Host: domain
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:3010
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Access-Control-Request-Headers: authorization,content-type
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
响应 header PDU -
HTTP/1.1 401 Unauthorized
Date: Mon, 08 Jan 2018 14:00:48 GMT
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: authorization,content-type
Access-Control-Allow-Method: POST,OPTIONS
WWW-Authenticate: Basic realm="Authentication Required"
Content-Length: 21
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
我收到 401(未经授权的错误),详细信息如下 -
zone.js:1981 选项 https://domain/login/api/system/sessions/ 401(未经授权)
:3010/#/login:1 加载失败 https://domain/login/api/system/sessions/ :对预检请求的响应未通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin” header 的值不得为通配符“*”。来源'http://localhost:3010 ' 因此不允许访问。 XMLHttpRequest发起请求的凭证模式由withCredentials属性控制。
任何人都可以帮我解决这个问题吗?
最佳答案
@vipul-goyal 对您帖子的评论几乎肯定是正确的答案 - 您的服务器正在检查 OPTIONS 预检请求中的有效授权请求 header 。
最简单的解决方案是绕过对 OPTIONS 请求的授权检查。这并不是真正的安全漏洞,特别是如果您只对预检 OPTIOSN 请求进行绕过(通过检查 method==OPTIONS
以及是否存在 Access-Control-Request-方法
请求 header )。对于任何其他 OPTIONS 请求,继续进行授权检查。
关于angular - OPTIONS 获取 401 - 预检请求未通过 Apache 上的访问控制检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48156166/