如何配置 Owin 以使用自定义 AuthenticationHandler?

How do I configure Owin to use a custom AuthenticationHandler?

have read 可以创建自定义 Owin 身份验证处理程序,但我不知道如何配置 Owin 以使用我的处理程序而不是默认处理程序。

如何告诉 Owin 使用此 class 而不是默认值?

public class XDOpenIdAuthHandler: OpenIdConnectAuthenticationHandler
{
    public XDOpenIdAuthHandler(ILogger logger)
        : base(logger)
    {
    }

    protected override void RememberNonce(OpenIdConnectMessage message, string nonce)
    {
        //Clean up after itself, otherwise cookies keep building up until we've got over 100 and
        // the browser starts throwing errors. Bad OpenId provider.
        var oldNonces = Request.Cookies.Where(kvp => kvp.Key.StartsWith(OpenIdConnectAuthenticationDefaults.CookiePrefix + "nonce")).ToArray();
        if (oldNonces.Any())
        {
            CookieOptions cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };
            foreach (KeyValuePair<string, string> oldNonce in oldNonces)
            {
                Response.Cookies.Delete(oldNonce.Key, cookieOptions);
            }
        }
        base.RememberNonce(message, nonce);
    }
}

您必须将其添加为自定义的一部分 AuthenticationMiddleware

public class CustomAuthMiddleware : AuthenticationMiddleware<OpenIdConnectAuthenticationOptions>
{
    public CustomAuthMiddleware(OwinMiddleware nextMiddleware, OpenIdConnectAuthenticationOptions authOptions)
        : base(nextMiddleware, authOptions)
    { }

    protected override AuthenticationHandler<OpenIdConnectAuthenticationOptions> CreateHandler()
    {
        return new XDOpenIdAuthHandler(yourLogger);
    }
}

然后在 Startup.Auth 中使用它,例如:

public partial class Startup
{
    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        app.Use<CustomAuthMiddleware>(new OpenIdConnectAuthenticationOptions());
    }
}

但是请注意,Owin 管道不得包含默认值 OpenIdConnectAuthenticationMiddleware,否则它仍将作为请求管道的一部分被调用。