Have you ever wondered how your user information gets to your action methods in MVC?

For example, when you use the Authorize attribute and you get authenticated users, and you can access their Name.

[Authorize] public ActionResult About() { var userName = User.Identity.Name; return View(); }

How did all this happen?

Well, first you probably started with File -> New Project -> ASP.NET MVC and selected Individual User Accounts. Or maybe you’re still using the old membership system and relying on the FormsAuthentication module. Whatever it is, the actual part of making the user information available is always the same, and it’s pretty simple.

It all boils down to two interfaces, IPrincial and IIdentity. A user being authenticated in ASP.NET just means that there is an instance of a class that implements IPrincipal and another that implements IIdentity in the current HttpContext.

One way to test this is to just create your own IPrincipal and IIdentity and set it in HttpContext.User. You can do this in Global.asax (for example in the Authenticate event) and see that everything works as if you’ve logged in using any of the usual forms of authentication (FormsAuthentication, Owin authentication middleware or ADFS, for example):

public class MvcApplication : System.Web.HttpApplication { public MvcApplication() { AuthenticateRequest += OnAuthenticateRequest; } private void OnAuthenticateRequest(object sender, System.EventArgs e) { var identity = new GenericIdentity("Rui", "AuthenticationType's Name"); var principal = new GenericPrincipal(identity, roles: new string[] { }); HttpContext.Current.User = principal; }

I have used GenericIdentity and GenericUser since these are the simplest implementations of IIdentity and IPrincipal.

This is what the FormsAuthentication module, owin authentication middleware, or if you are using ADFS, the SessionAuthentication module do for you, i.e. they set a principal and an identity in your HttpContext.

It's only fair to share... Linkedin