Asp.net-Mvc-5

使用asp.net身份更改目前使用者的使用者名後如何更改身份驗證cookie

  • October 13, 2013

將 asp.net 身份版本 1.0.0-rc1 與 Entity Framework 6.0.0-rc1(隨 Visual Studio 2013 RC 一起提供)一起使用。

試圖讓使用者有機會改變他們的UserName. 下似乎沒有該功能AuthenticationIdentityManager,因此我使用 EF 更改數據(獲取目前使用者的使用者對象,更改使用者名並保存更改)。

問題是身份驗證 cookie 保持不變,並且下一個請求失敗,因為沒有這樣的使用者。

過去通過表單身份驗證,我使用以下程式碼來解決這個問題。

var formsAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var isPersistent = FormsAuthentication.Decrypt(formsAuthCookie.Value).IsPersistent;
FormsAuthentication.SetAuthCookie(newUserName, isPersistent);

我應該如何處理 asp.net 身份來更新 cookie?

更新

以下程式碼似乎更新了身份驗證 cookie。

var identity = new ClaimsIdentity(User.Identity);
identity.RemoveClaim(identity.FindFirst(identity.NameClaimType));
identity.AddClaim(new Claim(identity.NameClaimType, newUserName));
AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant
   (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = false});

剩下的問題是:如何IsPersistent從目前的身份驗證 cookie 中提取值?

如何使用 AspNet.Identity 登錄/驗證具有 Asp.Net MVC5 RTM 位的使用者?

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
   AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
   var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
   AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

對於 RC1,您可以使用類似的程式碼。

AuthenticationManager.SignOut();
IdentityManager.Authentication.SignIn(AuthenticationManager, user.UserId, isPersistent:false);

對於持久值,您需要訪問身份驗證 cookie 並檢索狀態。

更新:

使用適當的 AuthenticationType 代替“Bearer”。還要確保在發出登錄票時,您正在設置 AuthenticationProperties.IsPersistent。

bool isPersistent=false;
var authContext = await Authentication.AuthenticateAsync("Bearer");
if (authContext != null)
{
  var aProperties = authContext.Properties;
  isPersistent = aProperties.IsPersistent;
}

引用自:https://stackoverflow.com/questions/19349011