Angular 6 - Add JWT bearer token to header not working

1.7k Views Asked by At

I'm trying to add the auth bearer token header while getting a comment from the asp.net core 2.2 backend in angular 6

getComment(postId: number): Observable<IComment[]>{
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    let authToken = localStorage.getItem('auth_token');
    headers.append('Authorization', 'Bearer ' + authToken);
    console.log(authToken);
    return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers });
  }

This piece of code is not working. I am getting a value from console.log(authToken). When I copy the token in Postman, everything is working fine.

My login function in a service. This is working fine to, i'm getting the token from the backend.

 login(login: ILogin) {
    console.log(login);
    return this.http
      .post('api/auth/login', login)
      .pipe(map((res: any) => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      }));
  }

When I remove authorization from the action in the backend, getting the comments is working fine. As you can see in the image below, the jwt token is just not being add to the header.

Postman: Postman

Header information from chrome Header Information

2

There are 2 best solutions below

1
On

You are not passing the headers in { headers } section. Change return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers }); to return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers: headers });

1
On

When you say it's working fine via Postman, and that this is not a CORS issue (i.e., either CORS is enabled, or your JS is being served from the same origin as you API), I assume you're already subscribing to the returned Observable<IComment[]>.

The code above won't issue the request until there is a call somewhere that looks like this:

yourService.getComment(postId).subscribe(comments => { ... });

That will begin consuming the Observable and trigger the underlying HTTP request.