2014-04-15 8 views
16

Ich möchte eine Art Countdown-Timer basierend auf der Zeit erstellen, die der OWIN-Cookie abläuft. Ich verwende OWIN mit MVC 5 und von dem, was ich verstehe SlidingExpiration ist standardmäßig aktiviert. Ich verwende keine "Sitzung", da ich diese App in einer Webfarm verwenden muss (ich plane nicht, eine Sitzungsdatenbank bereitzustellen).Wie kann man wissen, wann der OWIN-Cookie abläuft?

+0

Ist das nicht möglich? – FrankO

Antwort

29

Alles, was Sie brauchen, ist die CookieValidateIdentityContext während der Cookie-Validierung zu erreichen. Sobald Sie es bekommen, extrahieren Sie, was Sie brauchen, und behalten Sie sie als Claim oder eine andere Art, die Sie bevorzugen.

Für MVC 5 mit Asp.NET Identity 2.0, müssen Sie zwei Schritte ausführen:

  1. Definieren von benutzerdefinierten OnValidateIdentity, Cookie-Informationen extrahieren, und halten Sie sie als 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); 
        } 
    } 
    
  2. Zugriff auf Ihre Claim in Ihrem Controller-Methoden

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

Ich benutze diesen Ansatz meiner Anwendung Benutzer daran zu erinnern, ihre Sitzung vor Sitzungszeit hinaus zu verlängern.

Credit zu diesem Beitrag senden How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?

+0

Haben Sie ein Arbeitsprojekt, in dem dieser Code ausgeführt wird? Schwierigkeiten zu verstehen, was mit ar tun stampValidator = SecurityStampValidator.OnValidateIdentity . MyUser> (TimeSpan.FromSeconds (100), null); da ich keine Benutzer-Manager-Klasse und meine Benutzerklasse lediglich ein DTO – InTheWorldOfCodingApplications

+0

habe, verwende ich diesen Ansatz, um meine Anwendungsbenutzer daran zu erinnern, ihre Sitzung vor dem Sitzungszeitlimit zu verlängern. - Wie erhalten Sie die Ablaufzeit, ohne sie zu verlängern? Vielleicht verwandt - haben Sie slidingexpiration aktiviert? – mlhDev

Verwandte Themen