我已经在IIS 10上托管的.NET Core 3.1(.201)Web API中配置了IIS CORS Module,现在我对Windows身份验证用户的GET(不是OPTIONS)请求有了401 Unauthorized
,<在控制器或操作级别使用[Authorize]
属性来增强或减弱。 Swagger经过了一次尝试,在同一操作上返回200,因此我认为授权有效,因此问题一定与CORS有关。
我已经看到了一些变通方法,可以在Startup.cs
中启用匿名身份验证并设置一些授权筛选器,但是我想坚持使用IIS CORS模块,因为它的设计目的是正确涵盖这种情况。
所以也许有人可以帮我弄清楚我在做什么错。
web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>
</system.web>
<location path="." inheritInChildApplications="false">
<system.webServer>
<cors enabled="true" failUnlistedOrigins="false">
<add origin="http://localhost:4300" allowCredentials="true">
<allowHeaders allowAllRequestedHeaders="true">
<add header="credentials" />
</allowHeaders>
</add>
</cors>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="...\bin\Debug\netcoreapp3.1\MyProj.Api.exe" hostingModel="InProcess" forwardWindowsAuthToken="true">
<environmentVariables>
<environmentVariable name="COMPLUS_ForceENC" value="1" />
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
Startup.cs
services.AddAuthentication(IISDefaults.AuthenticationScheme);
...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles();
app.UseEndpoints(endpoints => ...
javascript请求(使用fetch API
)设置credentials: include
标头。
我也尝试过the approach suggested by Rick Strahl在他出色的网络日志中,但是得到了相同的结果:401
答案 0 :(得分:0)
您是否尝试过在Startup类中添加CORS?
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
...
}
在Configure方法中:
app.UseCors("CorsPolicy");
答案 1 :(得分:0)
您需要配置iis以处理cors请求。在web.config文件中设置以下代码:
<system.webServer>
<httpProtocol>
<customHeaders>
<!-- <add name="Access-Control-Allow-Origin" value="*" /> -->
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS,HEAD" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
</customHeaders>
</httpProtocol>
</system.webServer>
https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module