Dot-Net

如何知道 OWIN cookie 何時到期?

  • April 15, 2014

我想根據 OWIN cookie 過期的時間創建某種倒數計時器。我將 OWIN 與 MVC 5 一起使用,據我所知,預設情況下 SlidingExpiration 處於打開狀態。我不使用“會話”,因為我需要這個應用程序存在於網路場中(我不打算部署會話數據庫)。

CookieValidateIdentityContext您所需要的只是在 cookie 驗證階段掌握。一旦你得到它,提取你需要的任何東西,並以Claim你喜歡的方式或其他方式保存它們。

對於帶有 Asp.NET Identity 2.0 的 MVC 5,您需要執行兩個步驟:

  1. 定義自定義OnValidateIdentity,提取 cookie 資訊,並將其保存為Claim.
public class Startup
{
 public void Configuration(IAppBuilder app)
 {
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
     Provider = new CookieAuthenticationProvider
     {
       OnValidateIdentity = MyCustomValidateIdentity //refer to the implementation below
     }
   }
 }


 // this method will be called on every request
 // it is also one of the few places where you can access unencrypted cookie content as CookieValidateIdentityContext
 // once you get cookie information you need, keep it as one of the Claims
 // please ignore the MyUserManager and MyUser classes, they are only for sample, you should have yours
 private static Task MyCustomValidateIdentity(CookieValidateIdentityContext context)
 {
   // validate security stamp for 'sign out everywhere'
   // here I want to verify the security stamp in every 100 seconds.
   // but I choose not to regenerate the identity cookie, so I passed in NULL 
   var stampValidator = SecurityStampValidator.OnValidateIdentity<MyUserManager<Myuser>. MyUser>(TimeSpan.FromSeconds(100), null); 
   stampValidator.Invoke(context);

   // here we get the cookie expiry time
   var expireUtc = context.Properties.ExpiresUtc;

   // add the expiry time back to cookie as one of the claims, called 'myExpireUtc'
   // to ensure that the claim has latest value, we must keep only one claim
   // otherwise we will be having multiple claims with same type but different values
   var claimType = "myExpireUtc";
   var identity = context.Identity;
   if(identity.HasClaim(c=> c.Type == claimType))
   {
     var existingClaim = identity.FindFirst(claimType);
     identity.RemoveClaim(existingClaim); 
   }
   var newClaim = new Claim(claimType, expireUtc.Value.UtcTicks.ToString());
   context.Identity.AddClaim(newClaim);

   return Task.FromResult(0);
 }
}
  1. 訪問您Claim的控制器方法
// since expiry time has now become part of your claims, you now can get it back easily
// this example just returns the remaining time in total seconds, as a string value
// assuming this method is part of your controller methods

public string RemainingTime()
{
 var identity = User.Identity as ClaimsIdentity;
 var claimType = "myExpireUtc";  //NOTE: must be the same key value "myExpireUtc" defined in code shown above

 if(identity != null && identity.HasClaim(c=> c.Type == claimType))
 { 
   var expireOn = identity.FindFirstValue(claimType); 

   DateTimeOffset currentUtc = DateTimeOffset.UtcNow;
   DateTimeOffset? expireUtc = new DateTimeOffset(long.Parse(expireOn), TimeSpan.Zero);

   var remaining = (expireUtc.Value - currentUtc).TotalSeconds;

   return remaining.ToString();
 }
 return string.Empty;
}

我使用這種方法來提醒我的應用程序使用者在會話超時之前延長他們的會話。

歸功於這篇文章如何訪問 Microsoft.Owin.Security.xyz OnAuthenticated 上下文 AddClaims 值?

引用自:https://stackoverflow.com/questions/23090706