Home > OS >  Setting a bearer JWT token in Angular
Setting a bearer JWT token in Angular

Time:07-04

I am currently getting a 401 unauthorized error in the console for trying to access an API endpoint I built, which is protected. I noticed that I did not add the bearer token to the header.

I noticed this and added this in however I am still getting the 401 error, what am I doing wrong? I know the token is valid because I am testing in Postman and I get a 200 response code in Postman, but 401 in Angular.

Here is my code:

let token = localstorage.get('token');

  getCategories() : Observable<any> {
    let token = localStorage.getItem("token");

    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.set('Authorization', `Bearer ${token}`);

    
    return this.http.get(this.CategoriesUrl, { headers: headers} )
  }

CodePudding user response:

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So , you need to do the following:

  let headers = new HttpHeaders();
  header = header.set('Auth', 'Bearer '   token )

CodePudding user response:

Set vs Append - use append.

The append method appends a new value to the existing set of values for a header and returns a new instance. The append method does not check if the value exists.

The Sets method returns a new instance after modifying the given header. If the header already exists, its value is replaced with the given value in the returned object.

 headers.append('Authorization', `Bearer ${token}`);

Though I would suggest making an interceptor, to set the header for all queries.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

import { environment } from '@environments/environment';
import { AuthenticationService } from '@app/_services';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            
            const token = localStorage.getItem("token");

            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        

        return next.handle(request);
    }
}
  • Related