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);
request:
Preflight request:
CodePudding user response:
it is necessary to activate cors on the backend side so that it authorizes the front to use the apis
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
CodePudding user response:
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.
CodePudding user response:
This works for me... https://stackoverflow.com/a/55764660/10931383
Move the app.UseCors()
before these:
app.UseHttpsRedirection() app.UseDefaultFiles() app.UseStaticFiles() app.UseCookiePolicy()