-1

I have a .NET 6 Web API application that uses JWT authentication. The front end is an angular application. When I make an API call with the bearer token in the header, it returns the 401 error code. But with the same bearer token, I am able to call the same API from Swagger and get the expected data back.

I am using HttpClient to make the API calls:

import { HttpClient, HttpHeaders } from '@angular/common/http';
...
     
constructor(private httpClient: HttpClient
            private router: Router) { }
     
... 
const tokenHeader = new HttpHeaders({ "Authorization": `Bearer ${token}` }); 
const options = { headers: tokenHeader };  
return this.httpClient.post<any>(url, postParams, options);

error in the console enter image description here

request:

enter image description here

Preflight request:

preflight request

Ben Phung
  • 316
  • 4
  • 15
  • You have only shared the request headers. Could you share the full request details from the browser? – b.s Dec 30 '21 at 17:04
  • There was really no other details from the request... I added the preflight request details if that helps – Ben Phung Dec 30 '21 at 17:11
  • Yup, the OPTIONS call. Check my response. – b.s Dec 30 '21 at 17:15
  • Maybe [this](https://stackoverflow.com/a/26626522/2501279) can help? – Guru Stron Dec 30 '21 at 17:23
  • Hi Guru, my backend application only accepts origin from the angular application... – Ben Phung Dec 30 '21 at 17:51
  • What's the `DefaultAuthenticationScheme` specified in the `AddAuthentication` call? Do you specify `[Authorize(AuthenticationScheme = "bearer")]` on your controller or controller method? – Pieterjan Dec 30 '21 at 18:03
  • the `DefaultauthenticationScheme` is `JwtBearerDefaults.AuthenticationScheme`. All I needed to do was to move the `app.UseCors()` before the other `app.Usexx()` methods and it started to work. – Ben Phung Dec 30 '21 at 18:07

3 Answers3

1

This works for me... https://stackoverflow.com/a/55764660/10931383

Move the app.UseCors() before these:

app.UseHttpsRedirection()
app.UseDefaultFiles()
app.UseStaticFiles()
app.UseCookiePolicy()
Ben Phung
  • 316
  • 4
  • 15
0

it is necessary to activate cors on the backend side so that it authorizes the front to use the apis

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

Souhail HARRATI
  • 303
  • 2
  • 7
0

401 is for unauthorized requests. It's the browser that makes an OPTIONS call before making the actual request due to the CORS policy, but the browser doesn't send the Authorization header on this type of call. As you can see the OPTIONS request doesn't include the token so you need to make sure that your server doesn't respond with 401 to OPTIONS requests.

b.s
  • 2,409
  • 2
  • 16
  • 26
  • thanks Harry... I have been trying to google how to exclude the options calls from authentication but i haven't found anything useful... this is a .net core application. Do you know how do to that? – Ben Phung Dec 30 '21 at 17:47