Select Page

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.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).