在RegenerateIdentity期间,HttpContext.Current为null

时间:2014-12-03 11:10:35

标签: asp.net asp.net-identity identity claims-based-identity asp.net-identity-2

简介

我正在构建Identity 2.0的自定义实现。默认情况下,框架每30分钟刷新用户的身份,创建一个新的ClaimsIdentity。因为我有一些自定义声明(我在登录方法中设置),我想在刷新时转移到新的ClaimsIdentity,我想出了一种从{读取当前ClaimsIdentity的方法{1}}并将其作为“新”HttpContext返回。问题是,在刷新身份时ClaimsIdentity为空,因此我无法将旧的声明复制到新身份。

代码:

在我的HttpContext.Current文件中,我有这段代码,每x分钟刷新用户的身份:

Startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidatorExtensions.OnValidateIdentity( validateInterval: TimeSpan.FromMinutes(0.5), regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)) } }); func在我的RegenerateIdentity中调用此方法:

UserManager

问题:

第一次调用public async override Task<ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string authenticationType) { ClaimsIdentity claimsIdentity; if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated) { // Just return the existing ClaimsIdentity so we don't lose our custom claims claimsIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity; // TODO refresh some claims from the database return claimsIdentity; } // Create a new ClaimsIdentity if none exists claimsIdentity = await ClaimsIdentityFactory.CreateAsync(this, user, authenticationType); claimsIdentity.AddClaim(new Claim(Constants.DefaultSecurityStampClaimType, await GetSecurityStampAsync(user.Id))); return claimsIdentity; } (当我登录时),CreateIdentityAsync有一个值,创建了身份,一切都很好。问题是:当再次调用HttpContext.Current时(因为正在刷新身份),CreateIdentityAsyncHttpContext.Current。我不明白为什么会这样,我无法解决它。

理论

我对nullHttpContext.Current的原因的一些理论:

  1. 与异步有关,而null没有被转移到新线程?我尝试构建自己的awaiter来复制HttpContext,但这不起作用。
  2. 框架正在积极销毁HttpContext.Current以确保它摆脱一切?我无法找到任何代码来执行此操作,因此似乎不太可能。
  3. 有没有人对如何做到这一点有任何建议?

1 个答案:

答案 0 :(得分:0)

Cookie中间件在IIS管道中的身份验证阶段运行,该阶段在HttpContext或会话状态可用之前。所以你需要在没有它的情况下工作。

相关问题