3

简介:HttpContext.Current RegenerateIdentity期间是空

我建立身份2.0的自定义实现。默认情况下,框架每30分钟刷新用户的身份,创建一个新的ClaimsIdentity。因为我有一些自定义声明(我在我的登录方法中设置),我想在刷新时移动到新的ClaimsIdentity,我提出了一种方法,从HttpContext中读取当前的ClaimsIdentity,并将其作为“新” ClaimsIdentity。问题是当身份刷新时HttpContext.Current为空,所以我无法将我的旧版权声明复制到新身份。

代码:

在我Startup.cs文件我有这样的代码,刷新用户的身份每隔x分钟:

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

RegenerateIdentity FUNC调用此方法在我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有一个值,身份被创建,一切都很好。问题是:当再次调用CreateIdentityAsync时(因为身份正在刷新)HttpContext.Currentnull。我不明白这是为什么,我无法修复它。

理论:

一些我为什么HttpContext.Currentnull理论:

  1. 事做异步和HttpContext没有被转移到新的线程?我试图建立自己的服务员来复制HttpContext.Current,但那并不奏效。
  2. HttpContext正在被框架积极销毁,以确保它摆脱了一切?我一直无法找到任何代码,所以这似乎不太可能。

有没有人有任何建议如何做到这一点?

回答

0

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

相关问题