2

I'm building an Angular app that calls a .Net Core webapi. I have been able to set it up to be able to successfully call back and get a response with using CORS. But when I add the Authorization header to the Angular interceptor it throws the following error.

Error Access to XMLHttpRequest at 'http://localhost:57120/api/values' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

C# Startup - Configure method

app.UseCors(
            options =>
            {
                options.WithOrigins("http://localhost:4200");
                options.WithHeaders("Access-Control-Allow-Credentials: true"); 
                options.AllowCredentials();
            }
        );

Angular HttpInterceptor

const token =  localStorage.getItem('access-token');
    
const clone = request.clone({
      headers: request.headers.set("Authorization", "Bearer " + token),
      withCredentials: true,
      
});

return next.handle(clone);
jhorton
  • 1,019
  • 3
  • 17
  • 36
  • Can you verify that headers are being returned in postman? Note that if your code breaks before headers are sat then you will get cors error instead of http error – Metabolic Nov 09 '20 at 19:29
  • 1
    I've never used Postman. I can try to figure it out. – jhorton Nov 09 '20 at 19:39
  • So here's a kicker, my work blocks postman. But from what I can tell there doesn't appear to be any errors being thrown. It works without the line to add the authorization header, and doesn't when I add it. – jhorton Nov 09 '20 at 20:12
  • sanity check on your middleware order: is your CORS middleware before your authorization middleware (it should be)? – egnomerator Nov 09 '20 at 20:25

1 Answers1

0

You have a wrong startup configuration . Try to use a named cors policy and change your app.UserCors to anotner syntax:

  app.UseCors("CorsPolicy") 

services.AddCors(opt =>  opt.AddPolicy("CorsPolicy", c =>
            { 
                c.AllowAnyOrigin()
                   .AllowAnyHeader()
                    .AllowCredentials()
                    .AllowAnyMethod();
            }));

If it works you then can replace c.AllowAnyOrigin() by options.WithOrigins("http://localhost:4200");

Serge
  • 40,935
  • 4
  • 18
  • 45
  • 1
    I still used the app.UseCors() method, but included the same options as you have. I gave you the answer because it works. Thank you again. – jhorton Nov 09 '20 at 20:44