C# Asp.net核心web api使用windows身份验证-Cors请求未经授权
在我的asp.net核心web api中,我已经按照中的文章配置了Cors。web api应用程序正在使用windows身份验证(未启用匿名身份验证)。创建Cor的策略,并在C# Asp.net核心web api使用windows身份验证-Cors请求未经授权,c#,rest,.net-core,asp.net-web-api2,C#,Rest,.net Core,Asp.net Web Api2,在我的asp.net核心web api中,我已经按照中的文章配置了Cors。web api应用程序正在使用windows身份验证(未启用匿名身份验证)。创建Cor的策略,并在startup.cs public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("CorsPolicy",
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Enable CORS policy
app.UseCors("CorsPolicy");
app.UseMvc();
}
还应用了每个控制器级别的策略
[EnableCors("CorsPolicy"), Route("api/[controller]")]
public class LocationController : BaseController<Location>
{
//code
}
[EnableCors(“公司政策”),路由(“api/[controller]”)
公共类LocationController:BaseController
{
//代码
}
选项请求未经授权。请求和响应如下所示
我见过类似的问题,尝试过几乎所有的解决方案,但选项请求仍然失败 您可能需要阅读此线程:。您可以混合使用匿名和NTLM,这样您的CORS预授权就不会被拒绝(因为它们不包括windows凭据)。IIS甚至在到达中间件之前就处理NTLM身份验证,因此这可能是IIS的事情。您可能需要允许匿名CORs飞行前检查。这非常类似于我提供的解决方案(POST请求中出现401错误)。此外,不应同时配置NTLM和协商() 请检查添加凭据/允许用户凭据
允许跨源凭据时要小心。另一个域的网站可以在用户不知情的情况下代表用户向应用程序发送登录用户的凭据。CORS规范还规定,如果存在访问控制允许凭据标头,则将源代码设置为“*”(所有源代码)无效。使用IIS CORS模块出色地解决了此问题。以下网址仅供参考
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy("MyCustomCorsPolicyName",
builder => builder.WithOrigins("http://YourDomainName/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
....
app.UseCors("MyCustomCorsPolicyName");
app.UseMvc();
}
使用Windows身份验证
虽然这绝不是CORS模块解决的唯一方案,但它非常重要,值得调用。以前,如果您试图向使用Windows身份验证的应用程序发出跨域请求,您的飞行前请求将失败,因为浏览器未随飞行前请求发送凭据。如果不在应用程序中启用匿名身份验证,就无法解决此问题。由于CORS模块在身份验证之前启动,因此可以在不影响应用程序安全模型的情况下处理飞行前请求。下面是web.config的示例
示例代码:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<system.web>
<authentication mode="Windows"/>
</system.web>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="http://localhost:60096" allowCredentials="true" >
<allowHeaders allowAllRequestedHeaders="true">
<add header="Header1" />
</allowHeaders>
</add>
</cors>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\Project.Api.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>
经过几个小时的思考,这里有一个完整的解决方案(从前端到后端): 我的问题是:当我在我的web API上启用windows身份验证时,我无法从我的react应用程序获取对我的.NET Core 3.1 web API的调用,CORS吓坏了。使用匿名身份验证时,它起作用,但在启用windows身份验证时则不起作用 1.launchSettings.json 这将仅用于您的开发环境,请确保在prod服务器的IIS中也启用了windows身份验证
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:58747",
"sslPort": 0
}
},
{... more settings if any}
}
2.Startup.cs:
这里启用了CORS策略。方法的顺序在这里很重要。此外,您不需要在web.config中设置它们
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", //give it the name you want
builder =>
{
builder.WithOrigins( "http://localhost:3000", //dev site
"production web site"
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
//database services here
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
// global policy same name as in the ConfigureServices()
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
3.控制器:
using Microsoft.AspNetCore.Cors;
... your other usings
namespace ProjectTest.Controllers
{
[ApiController]
[EnableCors("CorsPolicy")] //THIS HERE needs to be the same name as set in your startup.cs
[Route("[controller]")]
public class FooController:Controller
{
[HttpGet("getTest")]
public JsonResult GetTest()
{
return Json("bar");
}
}
}
4.React组件获取调用示例:
using Microsoft.AspNetCore.Cors;
... your other usings
namespace ProjectTest.Controllers
{
[ApiController]
[EnableCors("CorsPolicy")] //THIS HERE needs to be the same name as set in your startup.cs
[Route("[controller]")]
public class FooController:Controller
{
[HttpGet("getTest")]
public JsonResult GetTest()
{
return Json("bar");
}
}
}
“凭证:'包括'”是秘密
await fetch('http://localhost:3000/Foo/getTest', {
method: 'GET',
credentials: 'include'
}).then(resp => resp.json());
1)在launchSettings.json文件(开发设置文件)中将允许Windows和匿名身份验证标志设置为true。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy("MyCustomCorsPolicyName",
builder => builder.WithOrigins("http://YourDomainName/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
....
app.UseCors("MyCustomCorsPolicyName");
app.UseMvc();
}
匿名身份验证:需要匿名身份验证才能允许飞行前选项请求
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iis":
...
}
2)在配置服务方法中添加Cors策略。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy("MyCustomCorsPolicyName",
builder => builder.WithOrigins("http://YourDomainName/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
....
app.UseCors("MyCustomCorsPolicyName");
app.UseMvc();
}
3:将CORS中间件添加到web应用程序管道中,以允许跨域请求。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy("MyCustomCorsPolicyName",
builder => builder.WithOrigins("http://YourDomainName/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
....
app.UseCors("MyCustomCorsPolicyName");
app.UseMvc();
}
4)在控制器顶部添加Authorize属性,以强制客户端发送凭据
[Authorize]
public class MyAPIController : ControllerBase
{
...
}
5)在JQuery或您正在使用的任何客户端中,将凭据属性标志设置为true
$.ajax({
type: "POST",
datatype: "json",
url: "YourApiUrl",
xhrFields: {
withCredentials: true
}
这对我在使用.net core 2.2、IIS Express和Windows身份验证的开发环境中起到了作用。注意:CORS中间件在IIS中不起作用。请参见此线程
web.release.config
不确定这是否有帮助,但我遇到了允许CORS请求访问和我构建的API的问题。我在阳光下尝试了一切,但结果表明,选项请求被IIS拒绝。您是否已在IIS或IIS设置中禁用匿名身份验证?您如何配置身份验证?我正在通过visual Studio中的web项目属性设置进行配置studio@KyleB我已通过VisualStudioSetting在web项目设置中禁用匿名身份验证
windowsAuthentication:true
和匿名身份验证:true
有效。