微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我非常沮丧的是,在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>();

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐