2014-04-15 16 views
16

Tôi muốn tạo một số loại đồng hồ đếm ngược dựa trên thời gian cookie OWIN sẽ hết hạn. Tôi đang sử dụng OWIN với MVC 5 và từ những gì tôi hiểu SlidingExpiration được bật theo mặc định. Tôi không sử dụng 'phiên' như tôi cần ứng dụng này để sống trong một trang trại (tôi không có kế hoạch triển khai một cơ sở dữ liệu phiên).Làm thế nào để biết khi nào cookie OWIN sẽ hết hạn?

+0

Điều này là không thể? – FrankO

Trả lời

29

Tất cả những gì bạn cần là giữ lại số CookieValidateIdentityContext trong giai đoạn xác thực cookie. Một khi bạn nhận được nó, trích xuất bất cứ điều gì bạn cần và giữ chúng như Claim hoặc một số cách khác mà bạn thích.

Đối với MVC 5 với Asp.NET nhận dạng 2.0, bạn cần thực hiện hai bước sau:

  1. Xác định tùy chỉnh OnValidateIdentity, trích xuất thông tin cookie, và giữ nó như 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. Tiếp cận Claim trong các phương pháp điều khiển của bạn

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

tôi sử dụng phương pháp này để nhắc nhở người sử dụng ứng dụng của tôi để mở rộng phiên của họ trước khi thời gian phiên ra của bạn.

Tín dụng cho bài đăng này How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?

+0

Bạn có một dự án làm việc nơi mã này chạy không? Đấu tranh để hiểu phải làm gì với ar stampValidator = SecurityStampValidator.OnValidateIdentity . MyUser> (TimeSpan.FromSeconds (100), null); vì tôi không có lớp người quản lý người dùng và lớp người dùng của tôi chỉ là một DTO – InTheWorldOfCodingApplications

+0

'Tôi sử dụng phương pháp này để nhắc người dùng ứng dụng của tôi mở rộng phiên của họ trước khi hết giờ.' - làm thế nào để bạn có được thời gian hết hạn mà không cần mở rộng nó? Có lẽ liên quan - bạn đã bật tính năng trượt hết hạn chưa? – mlhDev

Các vấn đề liên quan