Injecting ClaimsPrincipal into Service / Business logic – layers (.NET Core)

So… You want to add authorization or atleast being able to figure out the username in the business logic layer.
What i’ve previously done is inject the username from the ui layer into the service-layer through input params on all methods (bad).
To inject the claimsprincipal in .NET Core we utilize the builtin IOC capabilities and simply
services.AddTransient(s => s.GetService<HttpContext>().HttpContext.User); in Startup.cs
with the above we can simply just state (in the constructor) that our service / class / what ever needs a ClaimsPrincipal

Note: This requires the user is authenticated AND that you are using Claims (obviously).

Building on this, we could do something like the following;
Create a new service interface something like ICurrentUserProvider, with a method like public YourUserModel GetCurrentUser().

Implement the provider, injecting ClaimsPrincipal, your DbContext and maybe a caching service.

The convert the ClaimsPrincipal to your YourUserModel save it to the cache and return it.

Leave a Reply

Your email address will not be published. Required fields are marked *