如何更新ASP.NET标识中的声明?

我正在为我的MVC5项目使用OWIN身份validation。 这是我的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); } 

如您所见,我将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)); } } 

当我尝试删除索赔,我得到这个exception:

声明“ http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata:101 ”无法删除。 它不是这个身份的一部分,或者是包含这个身份的委托人拥有的一个声明。 例如,在创build具有angular色的GenericPrincipal时,Principal将拥有该声明。 这些angular色将通过在构造函数中传递的身份公开,但实际上并不属于身份。 对于RolePrincipal存在类似的逻辑。

有人可以帮我弄清楚如何更新索赔?

我创build了一个基于给定ClaimsIdentity的扩展方法来添加/更新/读取声明

 namespace Foobar.Common.Extensions { public static class Extensions { public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return; // check for existing claim and remove it var existingClaim = identity.FindFirst(key); if (existingClaim != null) identity.RemoveClaim(existingClaim); // add new claim identity.AddClaim(new Claim(key, value)); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); } public static string GetClaimValue(this IPrincipal currentPrincipal, string key) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return null; var claim = identity.Claims.FirstOrDefault(c => c.Type == key); return claim.Value; } } } 

然后使用它

 using Foobar.Common.Extensions; namespace Foobar.Web.Main.Controllers { public class HomeController : Controller { public ActionResult Index() { // add/updating claims User.AddUpdateClaim("key1", "value1"); User.AddUpdateClaim("key2", "value2"); User.AddUpdateClaim("key3", "value3"); } public ActionResult Details() { // reading a claim var key2 = User.GetClaim("key2"); } } } 

您可以创build一个新的ClaimsIdentity ,然后使用此类索赔进行更新。

 set { // get context of the authentication manager var authenticationManager = HttpContext.GetOwinContext().Authentication; // create a new identity from the old one var identity = new ClaimsIdentity(User.Identity); // update claim value identity.RemoveClaim(identity.FindFirst("AccountNo")); identity.AddClaim(new Claim("AccountNo", value)); // tell the authentication manager to use this new identity authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant( new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true } ); } 

另一种(asynchronous)方法,使用Identity的UserManager和SigninManager来反映身份Cookie的变化(以及可选地从数据库表AspNetUserClaims中删除声明):

 // Get User and a claims-based identity ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); var Identity = new ClaimsIdentity(User.Identity); // Remove existing claim and replace with a new value await UserManager.RemoveClaimAsync(user.Id, Identity.FindFirst("AccountNo")); await UserManager.AddClaimAsync(user.Id, new Claim("AccountNo", value)); // Re-Signin User to reflect the change in the Identity cookie await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // [optional] remove claims from claims table dbo.AspNetUserClaims, if not needed var userClaims = UserManager.GetClaims(user.Id); if (userClaims.Any()) { foreach (var item in userClaims) { UserManager.RemoveClaim(user.Id, item); } } 

我也得到了这个例外,并且像这样清理了一些东西

 var identity = User.Identity as ClaimsIdentity; var newIdentity = new ClaimsIdentity(identity.AuthenticationType, identity.NameClaimType, identity.RoleClaimType); newIdentity.AddClaims(identity.Claims.Where(c => false == (c.Type == claim.Type && c.Value == claim.Value))); // the claim has been removed, you can add it with a new value now if desired AuthenticationManager.SignOut(identity.AuthenticationType); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, newIdentity); 

当我使用MVC5,并在这里添加索赔。

 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(PATAUserManager manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim(ClaimTypes.Role, this.Role)); return userIdentity; } 

当我检查SignInAsync函数中的声明结果时,无论如何我都无法获取angular色值。 但…

在这个请求完成之后,我可以访问其他动作中的angular色(另一个请求)。

  var userWithClaims = (ClaimsPrincipal)User; Claim CRole = userWithClaims.Claims.First(c => c.Type == ClaimTypes.Role); 

所以,我想可能是asynchronous导致IEnumerable更新后面的过程。

扩展方法对我来说很好,除了一个例外,如果用户注销,那么旧的声明集仍然存在,只需进行一些微小的修改,就像在传递用户pipe理器通过一切正常的事情一样,你不需要注销和login。 我不能直接回答,因为我的名声已经消失:(

 public static class ClaimExtensions { public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value, ApplicationUserManager userManager) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return; // check for existing claim and remove it var existingClaim = identity.FindFirst(key); if (existingClaim != null) { RemoveClaim(currentPrincipal, key, userManager); } // add new claim var claim = new Claim(key, value); identity.AddClaim(claim); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); //Persist to store userManager.AddClaim(identity.GetUserId(),claim); } public static void RemoveClaim(this IPrincipal currentPrincipal, string key, ApplicationUserManager userManager) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return ; // check for existing claim and remove it var existingClaims = identity.FindAll(key); existingClaims.ForEach(c=> identity.RemoveClaim(c)); //remove old claims from store var user = userManager.FindById(identity.GetUserId()); var claims = userManager.GetClaims(user.Id); claims.Where(x => x.Type == key).ToList().ForEach(c => userManager.RemoveClaim(user.Id, c)); } public static string GetClaimValue(this IPrincipal currentPrincipal, string key) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return null; var claim = identity.Claims.First(c => c.Type == key); return claim.Value; } public static string GetAllClaims(this IPrincipal currentPrincipal, ApplicationUserManager userManager) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return null; var claims = userManager.GetClaims(identity.GetUserId()); var userClaims = new StringBuilder(); claims.ForEach(c => userClaims.AppendLine($"<li>{c.Type}, {c.Value}</li>")); return userClaims.ToString(); } } 

干得好:

  var user = User as ClaimsPrincipal; var identity = user.Identity as ClaimsIdentity; var claim = (from c in user.Claims where c.Type == ClaimTypes.UserData select c).Single(); identity.RemoveClaim(claim); 

从这里采取。