title: Custom principal in ASP.NET MVC
body: <p>I want to be able to access custom properties for an authenticated user like UserId and FirstName without querying the database each time.  I found <a href="http://webcache.googleusercontent.com/search?q=cache:HKMtchbXHEAJ:blog.codevelop.dk/post/2007/11/24/ASPNET-20-Forms-authentication-Keeping-it-customized-yet-simple.aspx+FormsIdentity+principal+httpcontext+unit+testing&amp;cd=23&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow noreferrer">this site</a> through a post on Stack Overflow and I like the approach - but I use IoC / repositories and decided not to try and get global.asax to communicate with the database for fear that it would be incompatible with the repository pattern.  </p>
  
  <p>Instead, I created an interface to CustomPrincipal and I use IoC (Castle) to create an instance and pass it to the controllers (and subsequently to my base controller).</p>
  
  <p>The base controller uses methods I created in CustomPrincipal to achieve the same task that the blog author addressed in global.asax.  Namely, CustomPrincipal is initialized from the database or cache and assigned to HttpContext.Current.User.</p>
  
  <p>My controllers/views can then reference the properties as follows...</p>
  
  <pre><code>((ICustomPrincipal)(HttpContext.Current.User)).FirstName;
  </code></pre>
  
  <p>It works, but I'm sensing some code smells.  First and foremost, if I reference HttpContext from the controllers I've killed my unit testing.  I'm thinking about modifying my CustomPrincipal object to return the above value (such that I can mock it in my unit tests) but I'm wondering if this is a workaround as opposed to a good solution.</p>
  
  <p>Am I going about this the right way?  Are there minor tweaks I could do to make it a robust solution or should I start from scratch with FormsAuthenticationTicket or something to that effect?</p>
  
  <p>Thanks!</p>