且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要求Asp.Net核心身份验证方案

更新时间:2023-11-30 23:42:46

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

After poring over the Asp.net Core security source code, I've managed to create a custom authentication handler. To do this you need to implement 3 classes.

第一个类实现了一个抽象的AuthenticationOptions.

The first class implements an abstract AuthenticationOptions.

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

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

The second class implements an abstract 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.

The third class implements an abstract 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方法中的中间件组件.

Finally, you use the middleware component in the Startup.cs Configure method.

app.UseMiddleware<AwesomeAuthenticationMiddleware>();

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

Now you can build your own Authentication Schemes.