locked
Add Remove Identity Claim RRS feed

  • Question

  • User1997618745 posted
    Dear All,
     
    We need to Remove and Add the existing claims stored in the Identity. 
    The below code works with asp.net 4.6. But When we try in asp.net core, we are getting ClaimsPrincipal.Current.Identities.First() as NULL value. 
    Please let us know How to Remove and Add the claims.. 
    Code Example
    var CP = ClaimsPrincipal.Current.Identities.First();
    foreach (System.Security.Claims.Claim appClaim in CP.Claims.ToList().Where(q => q.Type == "Claim1" || q.Type == "Claim2"))
    CP.RemoveClaim(appClaim);
     
    CP.AddClaim(new Claim("Claim1", Value1));
    CP.AddClaim(new Claim("Claim2", Value2)); 
     

    Monday, November 4, 2019 6:30 AM

Answers

  • User711641945 posted

    Hi Selvakumar,

    Please let us know How to Remove and Add the claims.

    Here is a simple demo like below:

    1.Controller:

    public class HomeController : Controller
    {
        private readonly CustomClaimsCookieSignInHelper<IdentityUser> _signInHelper;
        public HomeController(CustomClaimsCookieSignInHelper<IdentityUser> signInHelper)
        {
            _signInHelper = signInHelper;
        }
        public async Task AddClaim()
        {
            var user = User as ClaimsPrincipal;
            var identity = user.Identity as ClaimsIdentity;
            identity.AddClaim(new Claim("aaa", "bbb"));
            //If you want to save the claims to User.Claim, you need to call _signInManager.Context.SignInAsync with updated ClaimsIdentity
            await _signInHelper.SignInUserAsync(identity);
        }
        public async Task RemoveClaim()
        {
            var user = User as ClaimsPrincipal;
            var identity = user.Identity as ClaimsIdentity;
            var claim = (from c in user.Claims
                            where c.Type == "aaa"
                            select c).FirstOrDefault();
            identity.RemoveClaim(claim);
            await _signInHelper.SignInUserAsync(identity);
        }
    }

    2.CustomClaimsCookieSignInHelper:

    public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
    {
        private readonly SignInManager<TIdentityUser> _signInManager;
    
        public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
        {
            _signInManager = signInManager;
        }
        public async Task SignInUserAsync(ClaimsIdentity claimsIdentity)
        {
            await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
        }
    }

    3.Startup.ConfigureServices():

    services.AddTransient<CustomClaimsCookieSignInHelper<IdentityUser>>();
    

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 5, 2019 3:13 AM