ASP.net Core WEP Api中动态选择的认证方案 [英] Dynamically chose authentication scheme in ASP.net Core Wep Api

查看:46
本文介绍了ASP.net Core WEP Api中动态选择的认证方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将使用OWIN和.NET框架构建的自托管Web API移植到ASP.NET核心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.NegotiateNuGet包并配置:

了解了如何使用Windows身份验证
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
                .AddNegotiate();

但是,我不知道如何像以前那样动态选择是使用该方案还是允许基于标头的匿名呼叫。

这可能吗?我该怎么做?

推荐答案

以下是一种方法

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常量的身份验证方案。

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

这篇关于ASP.net Core WEP Api中动态选择的认证方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆