Prageeth godage
Prageeth godage

Reputation: 4554

Add Custom properties to ClaimsPrincipal user in asp.net core 2

As per description on title, I have created a class which derived from ClaimsPrincipal and have additional properties:

public class CustomeUser: ClaimsPrincipal
{
   // additional properties
}

Wrote a middleware and assigned values to that from the claims:

public async Task Invoke(HttpContext context)
{
   // context to read header and assign to custome properties
   context.User = new CustomeUser() {
                         ClientIP = /*reading from claims*/,
                         UserId = /*reading from claims*/};
}

and in configuration service add following line to get HttpContext to fetch that custom user properties from controller in start up class.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

from controller to fetch custome user properties

public BaseController(IHttpContextAccessor httpContextAccessor)
{
   customeUser = httpContextAccessor.HttpContext.User as CustomeUser;
}

Is this a correct approach?

Upvotes: 0

Views: 4054

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

You don't need IHttpContextAccessor if you access HttpContext from a controller. Microsoft.AspNetCore.Mvc.ControllerBase class from which controllers inherit (through Controller class) has HttpContext property. So your code could be changed as:

public BaseController()
{
   customeUser = HttpContext.User as CustomeUser;
}

All the rest seems good. HttpContext.User will contain instance of CustomeUser that you filled in Invoke() method so that nasty type conversion to CustomeUser will work just fine.

Upvotes: 4

Related Questions