angular - 具有 Windows 身份验证的 .NetCore 2.2 Web Api 从其他域返回 401
问题描述
在我写这篇文章之前,我花了很多时间搜索和尝试很多东西,但没有任何效果。这是一个 .NetCore 2.2 Web Api,我从 Angular 8 应用程序中使用它。
如果我从同一个域调用 web api,它工作正常。
如果我从其他域(或本地主机)调用 web api,它会返回 401(未经授权)。
如果我在禁用 Windows 身份验证的情况下从其他域(或本地主机)调用 Web api - 它工作正常(因此正确配置了 CORS)。
在我的launchSettings.json我有:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
在我的web.config我有:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" arguments="%LAUNCHER_ARGS%" />
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
</configuration>
在IIS中,我启用了 Windows 身份验证并禁用了匿名身份验证。
在我的Startup.cs中,我有:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
和
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseCors("CorsPolicy");
app.UseMvc();
}
我错过了什么?对此有什么想法吗?
解决方案
我假设对 Web API 的请求是从浏览器发起的?
使用 Windows 身份验证时需要 401 响应。然后客户端应使用正确的凭据重新发送请求。
可以将浏览器配置为自动发送当前登录用户的凭据。如果站点在 Internet 选项中的受信任站点列表中,IE 和 Chrome 将执行此操作。Firefox 有自己的network.negotiate-auth.delegation-uris
设置。
所以要么:
- 浏览器不信任该站点,因此它不会自动发送凭据,或者
- 您服务器的域不信任用户的域,因此即使浏览器发送当前用户的凭据,它们也会被第二个 401 响应拒绝。
推荐阅读
- presentation - 在 Google 幻灯片演示期间编辑文本
- c# - 如何将字符串渲染为剃刀?
- c - 为什么有正差时memcmp返回负值?
- haskell - Haskell 编译器如何“知道” IO 不能被解包?
- excel - Excel 工作簿中的字段之间的自动制表符
- javascript - 使用 Web API 检索块中的文件数据以在浏览器中显示 (WIP)
- gcc - 如何让 GCC 将“移动 r10,r3;存储 r10”组合成“存储 r3”?
- javascript - Vue 组件在 store 中更改自己的属性
- python - 如何旋转并将每列的平均值转换为行
- mysql - sequelize 不是唯一的表/别名