How can I register a custom Principal type in ASP.NET MVC 5?

Viewed 363

I have an application that is written using C# on the top of the ASP.NET MVC 5 framework.

Instead of using the built-in ClaimsPrincipal implementation of the IPrincipal interface, I want to used MyOwnClaimsPrincipal implementation. My MyOwnClaimsPrincipal class implements the IPrincipal interface.

In other words, I want to be able to access MyOwnClaimsPrincipal instance from inside of AuthorizeAttribute class or as the User Property in the controller and the views.

here is an example of what I want to be able to do

public class TestAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // This does not work
        MyOwnClaimsPrincipal user1 = filterContext.HttpContext.User as MyOwnClaimsPrincipal;

        // Yet, this works which tells me that my mplementation is not being used
        ClaimsPrincipal user2 = filterContext.HttpContext.User as ClaimsPrincipal;

    }
}

I tried to utilize Application_BeginRequest method in the Global.asax.cs to set the Thread.CurrentPrincipal and HttpContext.Current.User at the begining of each request like so

public void Application_BeginRequest()
{
    var user = new MyOwnClaimsPrincipal();//...

    Thread.CurrentPrincipal = user;
    HttpContext.Current.User = user;
} 

Unfortunately, that did not work. The filterContext.HttpContext.User is still set to ClaimsPrincipal and when I cast it as MyOwnClaimsPrincipal a null is returned.

How can I correctly set my one implementation of the IPrincipal to be used in the application?

1 Answers

I think you are to late according to this article Application_BeginRequest is the first event.

Just guessing: It seems the default authentification mechanism isn't checking if already an IPrincipal is assigned, so it overrides yours.

I have done the same using the Application_PostAuthenticateRequest Handler and it works fine:

protected void Application_PostAuthenticateRequest(object sender, EventArgs eventArgs)
{
    var claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.NameIdentifier, "42");
    claims.Add(new Claim(ClaimTypes.Name, "Hello World"));
    var claimsIdentity = new ClaimsIdentity(claims, "MylAuthentificationSheme");
    Context.User = new ClaimsPrincipal(claimsIdentity);
}
Related