2

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?

Tristan
  • 23
  • 4
  • you can use event-handling system https://learn.microsoft.com/en-us/sql/relational-databases/extended-events/extended-events?view=sql-server-2017#extended-events-tasks – Sultan Jun 28 '19 at 00:36
  • @Sultan I don't see how debugging tools for MSSQL will help me persists claims in my cookies. My question is entirely about .net-core. – Tristan Jun 28 '19 at 12:58

1 Answers1

0

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.

Rkaufman
  • 84
  • 1
  • 3
  • I will accept this answer as this a good solution for the criteria that I've set in my question. However, what I've realized is that there is no such things as having custom claims if they aren't in the database. You have to either add a column to the Users table or use the userManager to add it to the Claims table. It's easier to manage the lifetime of my organizationId if it's a new column of users. The securityStamp should also be invalidated if the user log in a different browser and choose a different organization to impersonate, which is good for my use case. – Tristan Jul 02 '19 at 13:46