Angular 8 - Difficulty recovering headers

Asked

Viewed 198 times

1

Save guys, I’m trying to get the header of the return of my http request to log in. In the header of this Response contains a key 'Authorization', but with the following code I am not able to get the value:

login(username, password) {
    return this.http.post<HttpResponse<any>>(`${environment.apiUrl}authenticate`, {},
        {
            observe: 'response',
            headers: {
                'Content-Type': 'application/json',
                'user': username,
                'key': password
            }
        })
        .pipe(tap(resp=> {
            console.log(resp.headers);
            console.log(resp.headers.get('Authorization'));
            console.log(resp.body);
            return resp.body;
        }));
}

Using the Postman the expected return happens. What could it be, I’m doing something wrong?

It is worth noting that my backend code is in Java and if I add some information in "body", the "console.log(Resp.body);" displays correctly, but the header continues without the information.

@POST
public Response login(@Context HttpHeaders headers) {
    Autenticator autenticator = Autenticator.getInstance();

    String user = headers.getHeaderString(Headers.USER);
    String key = headers.getHeaderString(Headers.KEY);
    UsuarioTO to = autenticator.login(user, key);
    return Response.ok()
            .header(HttpHeaders.AUTHORIZATION, Headers.BEARER + " " + to.token).build();
}

Thank you all.

1 answer

1


Try to add the following header in the answer. By default it is not exposed.

Access-Control-Expose-Headers: Authorization

Example:

@POST
public Response login(@Context HttpHeaders headers) {
    Autenticator autenticator = Autenticator.getInstance();

    String user = headers.getHeaderString(Headers.USER);
    String key = headers.getHeaderString(Headers.KEY);
    UsuarioTO to = autenticator.login(user, key);
    return Response.ok()
            .header(HttpHeaders.AUTHORIZATION, Headers.BEARER + " " + to.token).header("Access-Control-Expose-Headers", "Authorization").build();
}
  • Hello, I will test tonight and give an answer on. But already, thank you!

  • 1

    So boy, that’s right there, I checked my CORS filter and I really didn’t have this header added, too, I didn’t know it! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.