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

Nithin Paul

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?

Nithin Paul

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 :)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

I'm getting error 401 (unauthorized) while trying to make a GET request from my API that has a JWT token

Getting error autocomplete is not a function while fetching data from api?

Getting access token from the PayPal API Error

Angular 2 Error while fetching data from api

Getting 401 error due wrong placement of token jwt error

Getting 405 error instead of 401 while implementing authentication in ASP.NET Core Web API

Token already used error while fetching access token

Getting error while making access token request from Headers (Postman)

Getting [jwt is not defined] while fetching data from MongoDB backend -

Getting 401 error while requasting GitHub API

Error executing API while fetching folder list

Getting 401 when trying to access spotify web api with access token

Always getting 401 Error after implementing Basic Auth in Spring Security

While fetching nearby places from google places api. Getting an error The provided API key is invalid

BigtableConnection API failure;Error getting access token from metadata server at

Trouble while fetching data from API in Angular

Error while reading access token value from Web API response

Error while getting Dropbox access token of user

Certificate error while getting access token

Error getting access token for service account: 401 Unauthorized\nPOST https://oauth2.googleapis.com/token; Google Calendar API

Spotify API getting the error "No token provided" when fetching an endpoint

I am getting CORS error while fetching API from Node JS

GitHub API returns 401 while trying to generate access token

QWebEngineView & API access token fetching

Error while fetching refresh token from Azure AD

Angular getting Syntax Error: Token ':' is an unexpected token while accessing URLs from JSON

Getting keyerror while fetching JSON data from API using python

Getting an empty array in React while fetching the data from the api

Getting Encryption Error while parsing data fetching from Salesforce

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive