Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API get user identity in controller constructor

Is good idea to get user identity in ASP.NET Web API controller constructor, for example:

public PagesController(PageValidator pageValidator, PageMapper pageMapper, PagesManager pagesManager, UsersManager usersManager)
            :base(usersManager)
        {
          _pageValidator = pageValidator;
          _pageMapper = pageMapper;
          _pagesManager = pagesManager;
          if (User.Identity.IsAuthenticated)
            _pagesManager.UserId = usersManager.GetByEmail(User.Identity.Name).Id;
        }

Is always User.Identity was correct populated before this call raise?

like image 801
Alexey Z. Avatar asked Apr 01 '16 09:04

Alexey Z.


2 Answers

This has bitten me a few times. Depending on where/how you are performing your authentication, you need to be careful where you access your identity, particularly in controller constructors.

For example, whilst the controller action is invoked AFTER an IAuthenticationFilter is instantiated, the controller's constructor is called before AuthenticateAsync; meaning any authentication you do in AuthenticateAsync will not be available in your controller's constructor (like in your example).

I typically don't rely on things being available during controller construction (unless handled by DI). Instead access the identity as you need it in your controller actions.

If you are looking at making identity lookup easier (i.e. pulling in your user object based on the User.Identity.Name property) create a base controller class that has a property or method that does it for you, then have your controllers inherit from that...

public User AuthenticatedUser
{
    get
    {
        if (User.Identity.IsAuthenticated)
        {
            return usersManager.GetByEmail(User.Identity.Name);
        }

        return null;
    }
}

EDIT

See here for a detailed breakdown of the Web.API lifecycle, showing controller creation occurring prior to authentication.

like image 133
Aleks Avatar answered Sep 21 '22 16:09

Aleks


Yes. You can use this property in Controller in any place. ASP.NET has request pipeline: (http://www.dotnetcurry.com/aspnet/888/aspnet-webapi-message-lifecycle). As you can see Authorization is early stage step in request pipeline. Controller creation is the latest stage.

like image 40
Maksym Voronytskyi Avatar answered Sep 22 '22 16:09

Maksym Voronytskyi