为oauth / token请求剥离的基本授权标头

时间:2016-09-23 22:21:38

标签: angular cors spring-security-oauth2

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

客户端: 我有一个Angular2客户端作为一个单独的前端项目。我知道oauth / token post应该怎么样,因为我已经用Postman对它进行了测试。问题是Authorization标头被剥离而且它没有到达服务器。 注意:我在绝望的尝试中添加了这些Access-Control标头以使其工作。我不确定它是否有任何区别......

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

}

服务器 我使用" WebApplicationInitializer"开始使用Spring MVC应用程序,并在Initializer中注册了springSecurityFilterChain。 所有配置都通过注释完成,根本没有webapp内容。从嵌入式码头开始。

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

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

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

1 个答案:

答案 0 :(得分:2)

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

你可以通过这样做来解决它:

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));
相关问题