加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么强制使用Asp.Net核心认证方案

发布时间:2020-12-15 22:36:06 所属栏目:百科 来源:网络整理
导读:我非常沮丧的是,在Asp.Net Core中,身份验证方案似乎是强制性的. 我的目标是构建一个API,我不想知道客户端的任何信息.我已经建立了自定义身份验证和授权,工作正常.我没有使用身份或cookie.但是,如果没有有效的身份验证方案,我无法返回403 Forbid结果,否则我会
我非常沮丧的是,在Asp.Net Core中,身份验证方案似乎是强制性的.
我的目标是构建一个API,我不想知道客户端的任何信息.我已经建立了自定义身份验证和授权,工作正常.我没有使用身份或cookie.但是,如果没有有效的身份验证方案,我无法返回403 Forbid结果,否则我会收到以下异常…

System.InvalidOperationException: No authentication handler is
configured to handle the scheme: Automatic

我的问题是,我是否可以将MVC配置为不使用身份验证方案或创建身份验证方案而不依赖于登录路径或任何路径?

解决方法

在仔细阅读 Asp.net Core安全源代码之后,我设法创建了一个自定义身份验证处理程序.为此,您需要实现3个类.

第一个类实现抽象AuthenticationOptions.

public class AwesomeAuthenticationOptions : AuthenticationOptions {
    public AwesomeAuthenticationOptions() {
        AuthenticationScheme = "AwesomeAuthentication";
        AutomaticAuthenticate = false;
    }
}

第二个类实现了一个抽象的AuthenticationHandler.

public class AwesomeAuthentication : AuthenticationHandler<AwesomeAuthenticationOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var prop = new AuthenticationProperties();
        var ticket = new AuthenticationTicket(Context.User,prop,"AwesomeAuthentication");
        //this is where you setup the ClaimsPrincipal
        //if auth fails,return AuthenticateResult.Fail("reason for failure");
        return await Task.Run(() => AuthenticateResult.Success(ticket));
    }
}

第三个类实现了一个抽象的AuthenticationMiddleware.

public class AwesomeAuthenticationMiddleware : AuthenticationMiddleware<AwesomeAuthenticationOptions>
{
    public AwesomeAuthenticationMiddleware(RequestDelegate next,IOptions<AwesomeAuthenticationOptions> options,ILoggerFactory loggerFactory,UrlEncoder urlEncoder) : base(next,options,loggerFactory,urlEncoder) {

    }

    protected override AuthenticationHandler<AwesomeAuthenticationOptions> CreateHandler()
    {
        return new AwesomeAuthentication();
    }
}

最后,使用Startup.cs Configure方法中的中间件组件.

app.UseMiddleware<AwesomeAuthenticationMiddleware>();

现在,您可以构建自己的身份验证方案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读