[英]How to get response header with jwt token in Angular from server
我使用帶有 jwt 令牌的 spring 安全進行授權。 我發送帶有登錄名和密碼的 post 請求,並在授權字段中獲取帶有 jwt 令牌的響應標頭。
如何從 angular 獲取這個令牌? 我嘗試使用此代碼,但得到一個空值。 請幫忙。
login() {
const body = { username: this.user, password: this.pass };
this.http.post('http://localhost:8090/login', body, { observe: 'response'}).subscribe(
(response) => {
console.log(response.headers.get("Authorization"));
});
}
我認為您的進展順利,但您可能對后端服務器響應授權的CORS和標頭有疑問。
檢查此代碼,您收到的標題:
this.http.post('http://localhost:8090/login', body, { observe: 'response'}).subscribe(response => {
const keys = response.headers.keys();
const headers = keys.map(key =>
`${key}: ${response.headers.get(key)}`);
console.table(headers);
})
如果在控制台輸出中沒有看到任何Authorization
標頭,則應檢查后端配置。
您至少應該: - 使用 Spring Security 啟用 CORS - 添加默認的 CORS 映射
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("Authorization")
.allowCredentials(false).maxAge(3600);
}
在這里, Authorization
標頭在響應中公開。
我的建議是將公開的標頭限制為特定的端點,例如login
,並選擇另一個標頭,例如“x-auth-token for example, and send only token (not with
Bearer`)。
因為具有語法Bearer TOKEN
Authorization
用於從前端到后端的請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.