2015-10-20 26 views
5

Brock Allen's blog執行額外的驗證,他指出,使用OnValidateIdentity對Cookie數據

的CookieAuthenticationOptions類有一個Provider屬性...並 它有哪些是你可以訂閱的代表特性。這個 允許您驗證cookie進入應用程序 (OnValidateIdentity)。在此回調中,您可以拒絕或替換 身份。

我是新來OWIN和C#,所以我在努力適應,我已經在網上找到適合我的需求OnValidateIdentity的例子很多。餅乾已被認爲是有效的每個「私人」的網頁上,我想檢查以下東西:

  1. cookie包含至少一個聲明
  2. 在客戶要求值大於零

我可以在普通方法中實現這兩項檢查,但我無法弄清楚如何掛接登錄到OnValidateIdentity。這是我到目前爲止:

我寫了一些代碼,但無法弄清楚需要從使用的方法返回什麼。

public void Configuration(IAppBuilder app) 
{ 
    dynamic cookieExpirationPeriod = TimeSpan.FromMinutes(60); 

    CookieAuthenticationProvider prov = new CookieAuthenticationProvider(); 
    prov.OnValidateIdentity = ctx => 
    { 
     MyClaimsIdentityObject si = MyApp.Identity.Current(); 
     if (si == null || si.UserId == 0 || si.CustomerId == 0) { 
      ctx.RejectIdentity(); 
      // what needs to happen here for a return value? 
     } 
    }; 


    CookieAuthenticationOptions coa = new CookieAuthenticationOptions { 
     AuthenticationMode = AuthenticationMode.Active, 
     CookieName = "MyApp", 
     ExpireTimeSpan = cookieExpirationPeriod, 
     SlidingExpiration = true, 
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
     LoginPath = new PathString("/login.aspx"), 
     CookieHttpOnly = true, 
     Provider = prov 
    }; 

    if (HttpContext.Current.Request.IsLocal) { 
     coa.CookieSecure = CookieSecureOption.Never; 
    } else { 
     coa.CookieSecure = CookieSecureOption.Always; 
    } 

    app.UseCookieAuthentication(coa); 

} 

回答

3

我相信這只是:

return Task.FromResult<int>(0); 
+0

這裏有一個完整的例子,也實現了類似的事情,我需要什麼:http://stackoverflow.com/questions/25780551/extending-cookieauthenticationprovider- onvalidateidentity – EvilDr