Angular 4.3 HTTPClient 基本授权不起作用
2022-09-01 19:04:49
我正在尝试在使用新发布的.Angular 4
HttpClient
我正在尝试连接到运行的应用程序,该应用程序具有公开的API。Spring
Tomcat
REST
我的:LoginComponent
onSubmit(user){
console.log(user);
const body = JSON.stringify({username: user.userName, password: user.password});
let headers = new HttpHeaders();
headers.append("Authorization", "Basic " + btoa("username:password"));
headers.append("Content-Type", "application/x-www-form-urlencoded");
this.http.post('my url here',body, {headers: headers}).subscribe(response => {
console.log(response);
}, err => {
console.log("User authentication failed!");
});
}
但是,请求根本不添加标头。Authorization
这是从工具选项卡:Chrome
Network
我做错了什么?我怎样才能做到这一点?
更新1:它仍然不起作用:
我更改了我的两行,如下所示:
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
我按预期在请求中获取标头。这是从 :Chrome
但是,发布呼叫仍然失败。
在服务器端,我的代码是:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authCredentials = request.getHeader("Authorization");
if(authCredentials == null) {
logger.info("Request with no basic auth credentials {}", request.getRequestURL());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// do my stuff
}
呼叫永远不会到达 。 是。do my stuff
authCredentials
null
这是从 :chrome
如何进行?