Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Access User.Identity in Controller Constructor

I have a scenario where I need to access User.Identity Claims in my Constructor's Controller.

I need this because the Claims have information required for me to spin up a custom DB Context (Connection String)

How can I go about accessing this? I would just inject in the DBContext, but based on the user, they may need to access a different DB.

Is there a better way to think about this?

[Authorize]
public class DefaultController : Controller
{
    public DefaultController()
    {
        // this is NULL
        var authenticatedUser = User.Identity.Name;
    }
}
like image 754
aherrick Avatar asked Jun 27 '18 19:06

aherrick


1 Answers

As of version 2.1 of ASP.NET Core, HttpContextAccessor is provided. For this we must follow the following steps:

Configure the service using the standard implementation in the ConfigureServices method of Startup.cs:

services.AddHttpContextAccessor();

Perform the dependency injection of IHttpContextAccessor on the controllers. Use HttpContext property for access to User

[Authorize]
public class DefaultController : Controller
{
    public DefaultController(IHttpContextAccessor contextAccessor)
    {
        // Here HttpContext is not Null :)
        var authenticatedUser = contextAccessor.HttpContext.User.Identity.Name;
    }
}
like image 80
batressc Avatar answered Oct 20 '22 14:10

batressc