2013-10-13 114 views
18

将实体框架6.0.0-rc1(Visual Studio 2013 RC附带的)与asp.net身份版本1.0.0-rc1一起使用。如何使用asp.net身份更改当前用户的用户名后更改身份验证Cookie

试图让用户有机会改变他们的UserName。 似乎没有AuthenticationIdentityManager下的功能,所以我使用EF更改数据(获取当前用户的用户对象,更改用户名和保存更改)。

问题是身份验证Cookie保持不变,并且下一个请求失败,因为没有这样的用户。

在过去的表单验证我使用下面的代码来解决这个问题。

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

如何使用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}); 

剩下的问题是:如何提取当前验证cookie IsPersistent价值?

回答

15

How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?

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代替“承载”。同时请确保在发布登录票证时,您正在设置AuthenticationProperties.IsPersistent。

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

此代码可能适用于RTM(尚未广泛使用)。在RC1中没有DefaultAuthenticationTypes和UserManager.CreateIdentityAsync()。 – aleyush

+0

第二个问题:我如何获取当前的IsPersistent值(我的目标只是更改UserName,而不是其他任何内容)? – aleyush

+0

在发布VS2013之前,最好在每晚构建中进行试验。很少有开发人员发表的评论指出,许多RC1类在RTM中不可用,它将在11月份与VS2013一起发布。 – jd4u