Search code examples
c#asp.netasp.net-corecookiesasp.net-identity

Dynamic claims asp.net core identity no DB persistence


I'm setting up a system where after the user has logged in, he can choose to act on behalf of a certain organization. The user is presented with a list of organizations and he choose which one to 'impersonate'.

This information is dynamic and can change between login, so it mustn't persists in the database.

I figured out that I could try to add an additional claims to the user. I already use it to store some information. I achieve that by implementing my own UserClaimsPrincipalFactory and it's pretty straightforward since that information is persisted in the user and it doesn't change.

To add my organizationId claims, I tried different approach and none worked.

Adding the new claim directly in the User.Identity doesn't persists it on the next request.

Adding the new claim and signing in with the httpContext is also lost in the next request.

I assume this is all because of my UserClaimsPrincipalFactory.

The only way I found how to persist it for the session is by using the userManager.

await userManager.AddClaimAsync(user, new System.Security.Claims.Claim("organizationId", "myOrganization"));

However, the userManager save the data in the db and as I said at the start, this data is dynamic and changes between logins, it mustn't persists in the db.

I found this question on the subject: Store data in cookie with asp.net core identity

but unfortunately, the solution save the data in the database.

This question is similar to my use case but was left unanswered How to add claim to user dynamically?


Solution

  • I would recommend that you use a custom response header value or cookie to persist this value for a given session. See if this question helps: How to add a custom header

    Adding a cookie with the same expiration as the session expiration as in this post: Create a cookie Hope these help.