1
votes

I use spring security with jwt token for authorization. I send a post request with a login and password and get a response header with jwt token in the authorization field. enter image description here

How to get this token from angular? I tried to use this code, but I got a null value. Please help.

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
I think you got it the other way around. You need to send the token in the body and after that, you pass it to the authorization header (you can use an HTTP Interceptor). Then you check the token on your back-end and if is valid you authorize the request.ionut-t

1 Answers

1
votes

I think you're on the good track, but you probably have an issue about CORS and headers authorized in response by backend server.

Check with this code, the headers you received :

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);
})

If you don't see any Authorization header in console output, you should check your backend configuration.

For more details, see my answer on a question about CORS configuration.

You should at least : - enable CORS with Spring Security - add a default CORS mapping

@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);
}

Here, Authorization header is exposed in the response.

Note

My suggestion is to restrict exposed headers to a specific endpoint, login for example, and also to choose another header like 'x-auth-tokenfor example, and send only token (not withBearer`).

Because Authorization with syntax Bearer TOKEN is used for request from frontend to backend.