我試圖使用新發布的HttpClient
在Angular 4
實施基本授權。解決:角4.3 HTTPClient基本授權不起作用
我在嘗試連接到在Tomcat
上運行的Spring
應用程序,並在其中暴露了REST
API。
我在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
:
如何進行?
更新2:它的工作:
我不得不做這兩個步驟:
1)我不得不把headers
線改變什麼,我在更新1那樣,因爲HttpHeaders
是不可改變的。
headers = headers.append("Authorization", "Basic " + btoa("username:password"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
2)現在,根據您的需要,你有兩個選擇:
一)使用代理作爲解釋here解決CORS問題不改變你的服務器端。
b)按照here的說明更新服務器端,並在下面的一些答案中更改彈簧配置。
從包你進口'http' - '@角/普通/ http'或'@角/ http' –
@AjitSoman:@角/普通/ HTTP ... – Nik
難道Ben的回答工作你呢?你有沒有在控制檯上看到有關Cors的錯誤? –