ASP.NET MVC – Set custom IIdentity or IPrincipal

ASP.NET MVC – Set custom IIdentity or IPrincipal

Source

I decided to use IPrincipal instead of IIdentity because it means I don’t have to implement both IIdentity and IPrincipal.

  1. Create the interface
  2. CustomPrincipal

     
  3. CustomPrincipalSerializeModel – for serializing custom information into userdata field in FormsAuthenticationTicket object.

     
  4. LogIn method – setting up a cookie with custom information

     
  5. Global.asax.cs – Reading cookie and replacing HttpContext.User object, this is done by overriding PostAuthenticateRequest

     
  6. Access in Razor views

     

 

and in code:

I think the code is self-explanatory. If it isn’t, let me know.

Additionally to make the access even easier you can create a base controller and override the returned User object (HttpContext.User):

and then, for each controller:

which will allow you to access custom fields in code like this:

But this will not work inside views. For that you would need to create a custom WebViewPage implementation:

Make it a default page type in Views/web.config:

and in views, you can access it like this:

 

Leave a Reply