Marco Nuñez
Marco Nuñez

Reputation: 158

Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response with .net core and angular

I am trying to send the request from one localhost:4200 (front) to localhost:xx (back). I am using angular 8 on the frontend and .net core 2.2 on the backend.

In the backend use in the startup:

services.AddCors(options =>
{
   options.AddPolicy("AllowAllOrigins",
           builder => 
           builder.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials());
            });

app.UseCors("AllowAllOrigins");
app.UseAuthentication();
app.UseMvc();

The problem start when integrate the auth with jwt and in angular set in interceptor the bearer and token:

export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const currentUser = this.authenticationService.currentUserValue;
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}

For example doing it the request to the backend for login works, but after that get the error:

Access to XMLHttpRequest at 'http://localhost:1190/api/messagemapping' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Greetings and thanks for your help!

Upvotes: 2

Views: 4497

Answers (1)

Marco Nu&#241;ez
Marco Nu&#241;ez

Reputation: 158

The Anwers was remove AllowCredentials() like @R. Richards said!

Upvotes: 2

Related Questions