Search code examples
asp.net-mvcdependency-injectionwindows-authentication

How to insert/inject a fake user (IPrincipal)


We are required to use Windows authentication on a new project. So we will be utilizing the AuthorizeAttribute on action methods, and perhaps also within a limited number of controller actions.

Works great, of course. But to test this (both in unit testing, and in testing by hand as I integrate this stuff), I need to be able to simulate a user with any role, and to switch frequently back and forth between different roles.

I cannot modify the controller's User object (it's readonly), so from where can I insert a fake user that implements IPrincipal that to be accessed everywhere in my app, including:

  • in controller-actions
  • in custom attributes

I have not yet dived into DI frameworks -- will one be necessary at this point? If you strongly recommend so, I'd still like to know how to do this via "poor-man's" DI.


Solution

  • In global.asax / Application_PostAuthenticateRequest(object sender, EventArgs e).

    That method is invoked after ASP.NET have had it's fun with the principal.

    If you only want to provide your own roles you could just implement a RoleProvider instead.

    Update

    You can do this:

    public void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var principal = LoadFromTheDb();
        HttpContext.Current.User = Thread.CurrentPrincipal = principal;
    }
    

    And then you can use that principal wherever you like.

    If you have enabled runAllManagedModulesForAllRequests in web.config you should probably check if the user is authenticated first before doing anything else.