[英]Accessing cookie expiration time owin
我正在嘗試使用以下示例訪問Owin的到期時間
訪問Owin Cookie身份驗證的ExpireTimeSpan屬性,以通知用戶登錄到期
但我不能上班。 密鑰錯誤,值確實存在。 如果有人能指出正確的方向,我將非常感謝。
StartupAuth.cs
var config1 = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
};
app.UseCookieAuthentication(config1);
var options = new CookieAuthenticationOptions
{
// usual options such as LoginPath, for example, go here...
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = context =>
{
DateTimeOffset now = DateTimeOffset.UtcNow;
context.OwinContext.Request.Set<double>("time.Remaining",
context.Properties.ExpiresUtc.Value.Subtract(now).TotalSeconds);
return Task.FromResult<object>(null);
}
}
};
app.UseCookieAuthentication(options);
控制者
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
//var secondsRemaining = (double)Request.GetOwinContext()
// .Environment["time.Remaining"];
return View();
}
}
這個答案有另一種存儲值的方法。 它將其存儲為索賠。 您可以嘗試以下方法: 如何知道OWIN Cookie何時到期?
這是SlidingExpiration
但是很丑..它說明了SlidingExpiration
邏輯..請注意,在我的情況下,登錄請求中的聲明為空,因此我將其設置為sessionTimeInMinutes
SlidingExpiration = true,
CookieName = applicationCookieName,
Provider = new CookieAuthenticationProvider
{
// Not called on signin
OnValidateIdentity = context =>
{
// this is the last value before ExpireTimeSpan will update and its not reflected here
var expiresUtc = context.Properties.ExpiresUtc;
if ( expiresUtc == null) return Task.FromResult(0);
var sessionExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(sessionTimeInMinutes);
var expiresDifferenceSeconds =
sessionExpiresUtc.ToUnixTimeSeconds() - expiresUtc?.ToUnixTimeSeconds();
var expires = sessionTimeInMinutes * 60 / expiresDifferenceSeconds < 2
? sessionExpiresUtc
: expiresUtc;
context.Identity.UpdateClaim(CustomClaimTypes.Expires, expires.ToString());
return Task.FromResult(0);
}
}
然后我有一個過濾器,添加了應用程序使用的過期Cookie
DateTimeOffset expires;
if (identity.HasClaim(c => c.Type == CustomClaimTypes.Expires))
{
expires = DateTimeOffset.Parse(identity.FindFirstValue(CustomClaimTypes.Expires));
}
else
{
expires = DateTimeOffset.UtcNow.AddMinutes(sessionTimeInMinutes);
}
var cookieHeaderValues = new List<CookieHeaderValue>
{
new ApplicationCookeHeaderValue("session.expiresAt", expires.ToString("u"), expires),
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.