我正在为我的MVC5项目使用OWIN身份验证.这是我的SignInAsync
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
var AccountNo = "101";
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.UserData, AccountNo));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent, RedirectUri="Account/Index"}, identity);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我添加AccountNo到声明列表中.
现在,如何在我的应用程序中的某个时刻更新此声明?到目前为止,我有这个:
public string AccountNo
{
get
{
var CP = ClaimsPrincipal.Current.Identities.First();
var Account= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData);
return Account.Value;
}
set
{
var CP = ClaimsPrincipal.Current.Identities.First();
var AccountNo= CP.Claims.FirstOrDefault(p => p.Type == ClaimTypes.UserData).Value;
CP.RemoveClaim(new Claim(ClaimTypes.UserData,AccountNo));
CP.AddClaim(new Claim(ClaimTypes.UserData, value));
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试删除声明时,我得到以下异常:
声明' http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata:101 …
将asp.net身份版本1.0.0-rc1与Entity Framework 6.0.0-rc1(Visual Studio 2013 RC附带的那些)一起使用.
试图让用户有机会改变他们的UserName.似乎没有功能AuthenticationIdentityManager,所以我使用EF更改数据(获取当前用户的User对象,更改UserName并保存更改).
问题是认证cookie保持不变,下一个请求失败,因为没有这样的用户.
在过去的表单身份验证中,我使用以下代码来解决此问题.
var formsAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var isPersistent = FormsAuthentication.Decrypt(formsAuthCookie.Value).IsPersistent;
FormsAuthentication.SetAuthCookie(newUserName, isPersistent);
Run Code Online (Sandbox Code Playgroud)
我该怎么做asp.net身份更新cookie?
UPDATE
以下代码似乎更新了身份验证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});
Run Code Online (Sandbox Code Playgroud)
剩下的问题是:如何IsPersistent从当前身份验证cookie中提取值?