为 oauth/token 请求删除基本授权 header

Basic Authorization header stripped for oauth/token request

我的Oauth2授权有严重问题,四个晚上后我慢慢放弃了,所以我希望有人能帮助我。

客户: 我有一个 Angular2 客户端作为一个单独的 front-end 项目。我知道 oauth/token post 应该如何,因为我已经用 Postman 测试过了。问题是 Authorization header 被剥离并且它没有到达服务器。 注意:我拼命添加了 Access-Control headers 以使其工作。我不确定这是否有任何区别...

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Headers', 'Authorization');
headers.append('Authorization', 'Basic ' + Base64.encode('angularApp:theBiggestSecret'));

let options = new RequestOptions({ headers: headers });

this.http.post(`${this.baseUrl}oauth/token`, "grant_type=password&scope=read&username=test&password=test&client_id=angularApp&client_secret=theBiggestSecret", headers)
  .subscribe(
  response => console.log(response)
);

}

服务器: 我有 Spring MVC 应用程序以 "WebApplicationInitializer" 启动,springSecurityFilterChain 在 Initializer 中注册。 所有配置都是通过注释完成的,根本没有 webapp 内容。开始于嵌入式码头。

我在同一个应用程序中配置了 AuthorizationServer 和 ResourceServer,我通过 http.addFilterBefore 在 SecurityConfiguration 中配置了 CorsFilter,我可以看到它在工作。

问题: 好吧,我的授权 header 仍然被剥夺,所以基本身份验证不会 运行 而且我没有获得该访问令牌。但是,我相信 CORS 现在工作正常,我在浏览器中没有收到与 CORS 相关的错误,我可以将其视为响应 headers:

HTTP/1.1 401 Unauthorized
Date: Fri, 23 Sep 2016 21:41:34 GMT
Access-Control-Allow-Origin: *
Vary: Origin
Access-Control-Expose-Headers: Authorization, Content-Type
Cache-Control: no-store
Pragma: no-cache
WWW-Authenticate: Bearer error="unauthorized", error_description="There is no client authentication. Try adding an appropriate authentication filter."
Content-Type: application/json;charset=UTF-8
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Transfer-Encoding: chunked
Server: Jetty(9.3.11.v20160721)

这是在请求中发送的内容:

POST /oauth/token HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 115
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
content-type: text/plain
Accept: */*
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate
Accept-Language: cs-CZ,cs;q=0.8,en;q=0.6

您没有在 post() 方法中正确设置 headers

您可以通过这样做来修复它:

this.http.post(`${this.baseUrl}oauth/token`, '<form data>', { headers: headers })
    .subscribe(response => console.log(response));

您还可以在 URLSearchParams 对象中创建表单数据并将其设置为正文,这样 Angular 会自动为您将内容类型设置为 application/x-www-form-urlencoded

let body = new URLSearchParams();
body.set('grant_type', 'password');
body.set('scope', 'read');
body.set('username', 'test');
body.set('password', 'test');
body.set('client_id', 'angularApp');
body.set('client_secret', 'theBiggestSecret');

this.http.post(`${this.baseUrl}oauth/token`, body, { headers: headers })
        .subscribe(response => console.log(response));