添加授权时出现 CORS 错误 header

CORS Error When adding Authorization header

我正在构建一个调用 .Net Core webapi 的 Angular 应用程序。我已经能够将其设置为能够使用 CORS 成功回拨并获得响应。但是当我将授权 header 添加到 Angular 拦截器时,它会抛出以下错误。

错误 CORS 策略已阻止从来源 'http://localhost:4200' 访问位于 'http://localhost:57120/api/values' 的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:'Access-Control-Allow-Origin' header 不存在请求的资源。

C#启动-配置方法

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

您的启动配置有误。尝试使用命名的 cors 策略并将您的 app.UserCors 更改为另一种语法:

  app.UseCors("CorsPolicy") 

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

如果可行,您可以将 c.AllowAnyOrigin() 替换为 options.WithOrigins("http://localhost:4200");