ASP.NET Core Identity - How to add new claims after initial login

3.8k Views Asked by At

I am trying to add new claims to the Identity after the initial login based on certain data that is queried from database. The new claims that I am adding not persisting for subsequent requests.

This is how i'm setting/Adding claims in ASP.NET MVC

public static void UpdateClaim(IPrincipal principal, string key, string value)
        {
            var identity = principal.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 });
        }

Is there is similar way in ASP.NET Core 2.0 to persist newly added claims. Appreciate any ideas on this.

3

There are 3 best solutions below

0
Chris Pratt On

The claims are persisting, but they are only loaded when signing in. If you make a change to something like claims or roles, you must sign the user out and then either automatically sign them back in or prompt them to reauthenticated to update the claims.

3
Sarang Kulkarni On

Claims are not persisting if you are simply adding claims in Claims identity object in asp core, either you will have to use iClaimsTransformation or ClaimAction,

0
Lee Cichanowicz On

I think you have to refresh the user's sign-in, because Identity caches their claims upon sign-in for performance reasons.

In several pages from a scaffolded Identity integration, this line is used:

await _signInManager.RefreshSignInAsync(user);

You can see the (sparse) documentation here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinmanager-1.refreshsigninasync?view=aspnetcore-6.0

The concept is explained a bit here:

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims?view=aspnetcore-7.0#add-and-update-user-claims

call SignInManager.RefreshSignInAsync on a user to force the generation of a new authentication cookie.