How can I add a claim to the context.User.Claims when context.User is created?

David Thielen 3,211 Reputation points
2023-06-28T03:34:32.78+00:00

Hi;

This question is for the Identity library. My app is Blazor (server side) but I think that is irrelevant here.

Where is the context.User built in the Identity library? And can I add my own code in there?

I ask because I would like to add a claim to the context.User.Claims where the type is "Id" and the value is the AspNetUsers.Id guid for the user. Having this directly available from context.User would be super convenient.

I think this is connected to my question Identity library - Check Enabled & re-read Claims on each page because both require getting in to the Identity library code that builds the User object. I'm hoping there's a way, either with a defined middle-ware API, a method in the library I can directly edit, or some other approach.

thanks - dave

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-06-28T10:21:06.4133333+00:00

    According to you other posts, you're using cookie authentication. Rather than using the SignInManager which does all the work to fetch the claims and create the cookie you can write your own code to add whatever claims you like.

    Create an authentication cookie

    Remember .NET Core is open source. Just read the code.

    0 comments No comments

  2. Bruce (SqlWork.com) 78,086 Reputation points Volunteer Moderator
    2023-06-28T15:21:41.9466667+00:00

    the easiest way to add claims is to use the IClaimsTransformation interface. You define the transformation service and register, and it will be called when the User Principal is created.

    https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-7.0#extend-or-add-custom-claims-using-iclaimstransformation

    the issue you will have is that a Blazor Server App is that the user principal is created outside the Blazor app lifecycle. There is only one http request to create the connection (app instance), so the same HttpContext and user is used for the life of the Blazor App.

    in a classic web app which reads the cookie on every request, you would use ISecurityStampValidator if you wanted to detect changes in security information. but blazer server does not support this as the cookie is only loaded once.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.