简体   繁体   中英

Updating Claims Value in ASP.NET MVC

In the account login, I added values to the claims as

 // Initialization.    
 var claims = new List < Claim > ();
 try {
   // Setting    
   TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
   string nme = textInfo.ToTitleCase(Name.ToLower());
   string surN = textInfo.ToTitleCase(surName.ToLower());
   claims.Add(new Claim(ClaimTypes.Name, Name));
   claims.Add(new Claim("surName", surN));
   claims.Add(new Claim("Name", nme));
   claims.Add(new Claim("Customer_Id", Customer_Id));
   claims.Add(new Claim("User_Id", UserId));
   claims.Add(new Claim("TimeZone", timeZone));
   var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
   var ctx = Request.GetOwinContext();
   var authenticationManager = ctx.Authentication;
   // Sign In.    
   authenticationManager.SignIn(new AuthenticationProperties() {
     IsPersistent = false
   }, claimIdenties);
   var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

   var claimsPrincipal = new ClaimsPrincipal(identity);
   Thread.CurrentPrincipal = claimsPrincipal;

 } catch (Exception ex) {
   // Info    
   throw ex;

Now I want to update the Claims value in "Customer_Id" with a new value in another controller.

How do I update this claim?

I recently needed to achieve something similar. Add your claims to the IdentityModel where it says Add custom user claims here

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
   userIdentity.AddClaim(new Claim(ClaimTypes.Name, Name));
   userIdentity.AddClaim(new Claim("surName", surN));
   userIdentity.AddClaim(new Claim("Name", nme));
   userIdentity.AddClaim(new Claim("Customer_Id", Customer_Id));
   userIdentity.AddClaim(new Claim("User_Id", UserId));
   userIdentity.AddClaim(new Claim("TimeZone", timeZone));

Then insert this line just under the class definition at the top of the controller that you want to access the claims.

ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));

Now to modify the claim in any of your controller actions

ApplicationUser user = await userManager.FindByNameAsync("your username");
user.Customer_Id = "your new id";
await userManager.UpdateAsync(user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM