Angular2 Spring Boot JWT missing Response Header

只谈情不闲聊 提交于 2019-12-06 20:37:27

The browser does not expose custom headers to the app by default.

You will need the following header in your Backend Cors config

'Access-Control-Expose-Headers' 'Authorization';

Note that even if the headers are present in the dev console your app can't read them if they are not exposed by you server application.

Are you running your Angular2 app and springboot on a different port? If so, have you enable CORS in your springboot application?

Add withCredentials: true to your Angualr2 post header

this.http.post('http://localhost:9090/api/user/login', 
  { withCredentials: true },
  this.cred)

For more springboot JWT work with Angular, checkout Springboot JWT Starter

The Best way to solve your problem would be to add cors configurations in your application as described here https://spring.io/blog/2015/06/08/cors-support-in-spring-framework. You can also do it as follows:

@Configuration
public class RestConfigs {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addExposedHeader(MyUtils.AUTHENTICATION); //Header String
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

I had similar issue with Angular 6 and couldn't find solution for few days. After googling, frustrating, thinking and who knows what else I found the answer :)

At the end I had to switch to pure javascript and this solution works for me:

http.open('POST', url, true);

http.setRequestHeader('Content-type', 'application/json');
http.setRequestHeader('Accept', 'application/json, text/plain, */*');

http.onreadystatechange = function() {
  if (http.readyState == 4 && http.status == 200) {
    console.log('xhr:', http.getAllResponseHeaders());
  }
}
http.send(params);

http.getAllResponseHeaders() returns all headers similar like in web browser. Hope this will help you too.

I found well written post about CORS, which can cause troubles, on https://www.html5rocks.com/en/tutorials/cors/

Also as @evans-m said headers have to be exposed.

I am not still sure is it problem with Angular, browser or maybe even spring?!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!