2017-10-12 125 views
1

I have read它可以創建一個自定義的Owin身份驗證處理程序,但我無法弄清楚如何配置Owin使用我的處理程序而不是默認的處理程序。如何配置Owin使用自定義的AuthenticationHandler?

我該如何告訴Owin使用這個類而不是默認值?

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); 
    } 
} 

回答

1

您必須將其添加爲自定義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,否則將仍然可以稱爲請求的一部分管。

相關問題