我在ASP.net Core 2(Windows身份验证)上有一个API,并且在角度上有一个前端。 我做了一个cors配置来查询我的后端从SPA角度,但我阻止了因为他没有识别信息而被拒绝从IIS服务器的预检。
错误消息:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXXXXX' is therefore not allowed access. The response had HTTP status code 401.
代码方面:
//MY HEADER
private headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials':'true',
'Access-Control-Allow-Origin':'true'
});
//REQUEST
let options = new RequestOptions({headers:this.headers, withCredentials:true});
return this.http.get(this.tasksUrl,options).map(res=>res.json());
代码侧回:( Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("http://theURLofTheFront:8080" )
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("AllowSpecificOrigin");
app.UseMvc();
}
我试试这个:
CORS preflight request returning HTTP 401 with windows authentication
我添加了自定义标题以指定' Acces-control-allow-origin'在IIS上,不适合我。
这对我不起作用: https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/
我无法删除默认授权规则。
我提前感谢你
答案 0 :(得分:0)
有几种方法可以完成此操作,也可以在类似的问题上找到其他答案-> Angular4 ASP.NET Core 1.2 Windows Authentication CORS for PUT and POST Gives 401
可以使用CORS Module来配置IIS。
如此处所示:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
此处还有更多信息:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
IIS CORS模块旨在处理CORS飞行前请求 在其他IIS模块处理相同的请求之前。 OPTIONS请求 始终是匿名的,因此CORS模块为IIS服务器提供了一种 即使匿名,也可以正确响应预检请求 需要在服务器端禁用身份验证。
或者,可以通过在IIS中启用匿名身份验证并在Net Core API中创建一个用于检查人员是否经过正确身份验证的中间件来实现所需的结果。
中间件:
public AuthorizationMiddleware(RequestDelegate next, ILoggerFactory logger)
{
_next = next;
_log = logger.CreateLogger<GlobalExceptionHandler>();
}
public async Task Invoke(HttpContext httpContext)
{
//Allow OPTIONS requests to be anonymous
if (httpContext.Request.Method != "OPTIONS" && !httpContext.User.Identity.IsAuthenticated)
{
httpContext.Response.StatusCode = 401;
await httpContext.Response.WriteAsync("Not Authenticated");
}
await _next(httpContext);
}
答案 1 :(得分:-2)
预检请求不会发送身份验证信息。因此,也启用匿名身份验证(无需删除Windows身份验证)。参考https://stackoverflow.com/a/50354772/946773
答案 2 :(得分:-2)
我通过IIS模块Cors解决了我的问题