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或會話狀態變爲可用之前運行。所以你需要在沒有它的情況下工作。