如何从服务器获取Angular中带有jwt令牌的响应标头

时间:2020-03-24 15:45:18

标签: angular spring-security http-headers jwt jwt-auth

我使用带有jwt令牌的spring安全性进行授权。我发送带有登录名和密码的发布请求,并在授权字段中获得带有jwt令牌的响应标头。 enter image description here

如何从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"));
      });


 }

1 个答案:

答案 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}}用于从前端到后端的请求。