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);
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");