【问题标题】:Use both windows authentication and bearer tokens in one web api在一个 Web api 中同时使用 Windows 身份验证和不记名令牌
【发布时间】: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


    【解决方案1】:

    您可以添加多个 AuthenticationSchemes,因为它是一个逗号分隔的字符串属性。

    [Authorize(AuthenticationSchemes = "Windows,Bearer")]
    

    【讨论】:

    • 这不是我需要的,我需要每个控制器方法为每个方法只允许一个身份验证方案。
    • 您也可以在控制器中的每个动作中添加这个注解。
    猜你喜欢
    • 2014-10-13
    • 2017-08-16
    • 2018-06-03
    • 1970-01-01
    • 2014-01-24
    • 2014-11-20
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多