我使用带有jwt令牌的spring安全性进行授权。我发送带有登录名和密码的发布请求,并在授权字段中获得带有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"));
});
}
答案 0 :(得分:0)
我认为您步入正轨,但是您可能遇到有关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
标头,则应检查后端配置。
有关更多详细信息,请参阅my answer有关有关CORS配置的问题。
您至少应: -通过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`)。
因为语法Authorization
的{{1}}用于从前端到后端的请求。