【发布时间】:2022-01-05 18:48:22
【问题描述】:
我正在尝试在 .NET core 3.1 中构建一个 web api,它首先尝试通过 windows 身份验证获取承载令牌,然后使用此令牌来验证进一步的请求。
似乎不允许在单个 web api 控制器中同时使用 windows 身份验证和承载。我想拥有一个使用 Windows 身份验证而另一个使用承载身份验证的控制器。 这是我的控制器方法:
[HttpGet]
[Route("api/token")]
[Authorize(AuthenticationSchemes = "Windows")]
public async Task<IActionResult> AuthorizeAsync(CancellationToken cancellationToken)
{
// Do something
}
这是我的不记名身份验证方案:
_services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = !string.IsNullOrWhiteSpace(tokenProviderOptions.SigningKey),
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenProviderOptions.SigningKey)),
ValidateIssuer = !string.IsNullOrWhiteSpace(tokenProviderOptions.Issuer),
ValidIssuer = tokenProviderOptions.Issuer,
ValidateAudience = !string.IsNullOrWhiteSpace(tokenProviderOptions.Audience),
ValidAudience = tokenProviderOptions.Audience,
RequireExpirationTime = true,
ValidateLifetime = !string.IsNullOrWhiteSpace(tokenProviderOptions.TokenLifeTime),
ClockSkew = TimeSpan.FromSeconds(0),
};
});
在我的启动中,我添加了 windows auth:
services.AddAuthentication("Windows").AddNegotiate();
我已经阅读了您不能调用 AddAuthentication 两次的答案,因为第二次调用将覆盖第一次调用的配置,但这些问题中没有提供解决方案。
那么如何在一个 web api 控制器中混合 windows 身份验证和不记名令牌?
我找到的唯一可能的解决方案是覆盖 中间件,并且对于某些路径,将 401 覆盖为未知响应(例如:418)
我看过这个问题:ASP.Net Core 2.0 mixed authentication of JWT and Windows Authentication doesn't accept credentials
【问题讨论】:
标签: c# asp.net-core asp.net-web-api jwt