Prafulla
Prafulla

Reputation: 1

How to get 'Authorization' Header in Angular 5

I have Spring-Boot JWT enabled REST APIs. Authentication API /login does provide All the CORS and AUTH headers as expected. Tested with Curl and Postman. My Client code is in Angular 5. When successfully authenticated I can see -

  1. All the required headers, specifically 'Authorization' header in Developer Tools of Chrome in Network Traffic.
  2. However when accessed with Angular 5 HttpClient no Header is accessible in Component/Service.

Note: Backend side, CORS and Allow Headers is enabled, and hence Chrome Network Traffic is fine.

Added the required options in HttpClient during POST call.

{
     responseType: 'text',
     observe: 'response'
}

Tried with all possible responseType there. JSON, as default, throws Parse Exceptions. It means the default Spring-Boot JWTS /login API does not return JSON Output but returns only HttpResponse.

Please help...

Angular Code -

login(payload: any): Observable < any > {

    return this._http.post(this.loginEndPoint, payload, {
        responseType: 'text',
        observe: 'response'
    })
        /* .map((response: HttpResponse<string>) => {
            console.log(response.headers.get('Authorization'));
            return response;
        }); */
        .pipe(
        tap(response => {
            console.log(response.headers.get('Authorization'));
            return response;
        }),
        catchError(this.handleError('getHeroes', []))
        );
}

Upvotes: 0

Views: 2159

Answers (2)

rdma
rdma

Reputation: 1

You should add a line in your backend: response.addHeader("access-control-expose-headers", "Authorization");

Upvotes: 0

LLai
LLai

Reputation: 13416

The tap operator does not emit values in the observable stream. So returning something in it will not do anything. It is used to do side effect things like logging. To emit a value use the map operator

.pipe(
    map(response => {
       return response.headers.get('Authorization');
   })
)

Note: This only returns the header to the component that subscribed.

Upvotes: 0

Related Questions