如何知道什么时候OWIN cookie将到期? [英] How to know when OWIN cookie will expire?

查看:270
本文介绍了如何知道什么时候OWIN cookie将到期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建某种倒数计时的基于时间的OWIN cookie将到期。我使用OWIN与MVC 5和从我了解SlidingExpiration默认是打开的。我不使用会话,因为我需要这个应用程序的Web服务器场中生活(我不计划部署一个会话数据库)。

I would like to create some kind of countdown timer based on the time the OWIN cookie will expire. I am using OWIN with MVC 5 and from what I understand SlidingExpiration is on by default. I do not use 'session' as I need this app to live within a web farm (I dont plan on deploying a session database).

推荐答案

所有你需要的是在cookie验证阶段弄个 CookieValidateIdentityContext 的。一旦你得到它,提取无论你需要什么,并让他们为要求或其他方式,你preFER。

All you need is to get hold of the CookieValidateIdentityContext during the cookie validation stage. Once you get it, extract whatever you need and keep them as Claim or some other way that you prefer.

有关MVC 5与Asp.NET标识2.0,您需要执行两个步骤:

For MVC 5 with Asp.NET Identity 2.0, you need to perform two steps:

  1. 定义自定义 OnValidateIdentity ,提取cookie信息,并把它作为要求

  1. Define custom OnValidateIdentity, extract cookie information, and keep it as 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);
  }
}

在你的控制器方法

  • 访问您的要求

  • Access your Claim in your controller methods

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

  • 我用这种方式来提醒我的应用程序的用户他们的会话的会话超时之前延长。

    I use this approach to remind my application users to extend their session before session time out.

    感谢这个帖子<一个href="http://stackoverflow.com/questions/19456008/how-do-i-access-microsoft-owin-security-xyz-onauthenticated-context-addclaims-va">How我做访问Microsoft.Owin.Security.xyz OnAuthenticated方面AddClaims值?

    这篇关于如何知道什么时候OWIN cookie将到期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆