Nithin Paul
Nithin Paul

Reputation: 2199

Getting 401 Error while fetching list from API after implementing JWT access token in Angular

In my service .ts file i coded like this

getUsers(): Observable<any> {
    let httpOptions = new HttpHeaders().set('Authorization', 'Bearer ' + 
    this.securityService.securityObject.bearerToken);
    return this.http.get(environment.baseApiUrl + "user", { headers: httpOptions });
}

In the bearerToken we have token value, but the headers showing in the httpOptions is like below image. (took from the console)

enter image description here

in my controller class i have

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> Get()
    {

In my HttpInterceptor i have written like

  var token = localStorage.getItem("bearerToken");

  if (token) {
  const newReq = request.clone(
    {
      headers: request.headers
        .set('Authorization',
          'Bearer ' + token)
    });

  return next.handle(newReq);
}
else {
  return next.handle(request);
}

my local storage have my token value, but

When i debug the code what i can see is its not entering inside the clone is this is the reason for headers not any entries like my image. Is clone ok to use there?

Upvotes: 0

Views: 76

Answers (2)

Nithin Paul
Nithin Paul

Reputation: 2199

These were the main culprits which caused my issue

  1. Like corsaro mentioned interceptors will take care our http request no need to mention it separately

  2. In my startup.cs file i was using before like this

    app.UseAuthorization();
    app.UseAuthentication();
    

I swapped it's order to

   app.UseAuthentication();
   app.UseAuthorization();
  1. In my interceptor class i modified header section to this

     headers: new HttpHeaders({
         'Content-Type': 'application/json',
         'Authorization':'Bearer ' + token
       }) 
    
  2. Copied JwtSettings which declared in the appsettings.json file to appsettings.development.json file for local debug

Now after making these changes its working fine now :)

Upvotes: 0

corsaro
corsaro

Reputation: 773

i m use on the same way, i don't think it s this the problem, but i think you don't need to set also when you call the get user

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {

    constructor(private injector: Injector) { }

    token:string;

    intercept(req, next) {
        const authService = this.injector.get(AuthenticationService);

        this.token = authService.getToken();

        const authRequest = req.clone({
            headers: req.headers.set('Authorization', 'Bearer ' + this.token) 
        });

        return next.handle(authRequest);
    }
}

if you look on the tools network it s already set from Interceptor Only:

getUsers(): Observable<any> {
    return this.http.get(environment.baseApiUrl + "user")
}

Upvotes: 1

Related Questions