Asp.net-Mvc
在 MVC5 中的 Owin Identity 中重用聲明 regenerateIdentityCallback
我正在使用帶有 Owin 身份的 MVC5。
我正在努力在 regenerateIdentityCallback 中重用任何自定義聲明。
我在啟動時有這個配置(在新 MVC 項目的標準模板中提供)
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>( validateInterval: TimeSpan.FromSeconds(10), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback: (user) => Guid.Parse(user.GetUserId())) } });GenerateUserIdentityAsync 看起來像這樣:(以及模板中的標準)
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, Guid> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // I want here instead of generating new one, just reuse the previous one userIdentity.AddClaim(new Claim(ClaimTypes.Sid, Guid.NewGuid().ToString())); return userIdentity; }問題是,我無法重用聲明,我總是必須為它獲得新的價值。在調查了我看到的 Identity dll 之後,
this該使用者實例沒有聲明,因為它是來自數據庫的新使用者,並且userIdentity只有標準聲明作為 Id 和 UserName,它們是由 CreateIdentityAsync 方法創建的。從 HttpContext.Current 獲取使用者是不可能的,在這個地方它是空的。重用聲明以保留 Cookie 中的某些值的最佳方法是什麼?我可能誤解了索賠的目的。提前謝謝您的幫助
您可以通過這樣做獲得相同的結果(context.Identity 是以前的身份):
OnValidateIdentity = context => SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, DtbsUser, Guid>( validateInterval: TimeSpan.FromSeconds(30), regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager, context.Identity), getUserIdCallback: (ci) => Guid.Parse(ci.GetUserId())).Invoke(context)
我放棄並創建了自己的
SecurityStampValidator,它與原來的完全相同,但將目前的 claimIdentity 作為參數傳遞給 regenerateIdentityCallback。對此解決方案一點也不滿意,但它確實有效。OnValidateIdentity = MySecurityStampValidator.OnValidateIdentity<ApplicationUserManager, DtbsUser, Guid>( validateInterval: TimeSpan.FromSeconds(10), regenerateIdentityCallback: (manager, user, previousIdentity) => user.GenerateUserIdentityAsync(manager, previousIdentity), getUserIdCallback: user => Guid.Parse(user.GetUserId()))