【问题标题】:Dynamically chose authentication scheme in ASP.net Core Wep Api在 ASP.net Core Web Api 中动态选择身份验证方案
【发布时间】:2022-01-06 05:17:28
【问题描述】:

我正在将使用 OWIN 和 .NET Framework 构建的自托管 Web API 移植到 ASP.NET Core Web API(使用 .NET 6.0)

在原始 API 中,我有一个自定义身份验证机制,它根据请求中的标头为每个调用动态选择身份验证方案:

HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemeSelectorDelegate = new AuthenticationSchemeSelector((httpRequest) =>
{
    if(httpRequest.Headers.AllKeys.Any(k => k == "MyCustomHeader"))
    {
        return AuthenticationSchemes.Ntlm;
    }
    else
    {
        return AuthenticationSchemes.Anonymous;
    }
});

基本上,对于每个请求,我都会检查请求中的特定标头,并根据该标头选择是强制请求使用 Windows 身份验证还是允许请求匿名进行。

如何在 ASP.net Core Web api 中复制此行为?我通过使用Microsoft.AspNetCore.Authentication.Negotiate NuGet 包和配置了解了如何使用 Windows 身份验证:

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
                .AddNegotiate();

但是,我不知道如何像以前一样根据标头动态选择是使用该方案还是允许匿名调用。

这可能吗?我该怎么做?

【问题讨论】:

    标签: c# asp.net-core owin windows-authentication asp.net-core-authenticationhandler


    【解决方案1】:

    这是一种方法

    services.AddAuthentication(opts =>
        {
            opts.DefaultScheme = "DynamicAuthenticationScheme";
        })
        .AddScheme<SystemSessionAuthenticationRelatedOptions, SystemAuthenticationRelatedHandler>(
            CommonConstants.SessionAuthentication, x => x.Test = "Ran in here")
        .AddCookie("CookieScheme")
        .AddJwtBearer(options =>
        {
            options.Authority = identityUrl;
            options.Audience = "shipping";
            options.RequireHttpsMetadata = false;
        })
        .AddPolicyScheme("DynamicAuthenticationScheme", "Default system policy",
            cfgOpts => cfgOpts.ForwardDefaultSelector = ctx =>
                ctx.Request.Headers.ContainsKey("IsTheSecretHeaderPresent?")
                    ? "CookieScheme"
                    : JwtBearerDefaults.AuthenticationScheme);
    

    我们的想法是为DynamicAuthenticationScheme指定一个默认的身份验证方案,我们为Cookie和Jwt身份验证分别添加了两个名为CookieSchemeJwtBearerDefaults.AuthenticationScheme的身份验证方案。

    然后将我们的默认认证方案定义为基于头信息的认证机制的路由。

    【讨论】:

    • 谢谢,成功了!
    猜你喜欢
    • 2018-12-07
    • 2022-07-27
    • 2016-12-22
    • 2018-02-23
    • 2022-01-27
    • 2018-01-28
    • 2017-11-24
    • 2021-08-27
    • 2018-06-23
    相关资源
    最近更新 更多