title: ASP.NET web api - Set custom IIdentity or IPrincipal
body: <p>In our asp.net mvc/web api project, we want to customize the authorization using <code>AuthorizeAttribute</code>. We have noticed that there are two different <code>AuthorizeAttribute</code>, one in <code>System.Web.MVC</code> namespace for MVC and the other in <code>System.Net.Http</code> namespace for web api.</p>
  
  <p>It works in MVC, our code like this:</p>
  
  <pre><code>public class MyPrincipal : IPrincipal
  {
      //some custom properties
      public bool IsValid()
      {
          //custom authentication logic
      }
  
      private IIdentity identity;
      public IIdentity Identity
      {
          get { return this.identity; }
      }
  
      public bool IsInRole(string role)
      {
          return true;
      }
  }
  
  //override AuthorizeCore
  public class MyAuthorizeAttribute : AuthorizeAttribute
  {
      protected override bool AuthorizeCore(HttpContextBase httpContext)
      {
          MyPrincipal user = new MyPrincipal();
  
          if (user.isValid())
          {
              httpContext.User = user;
          }
          else
          {
              httpContext.Response.Redirect("~/Common/NoAuthorize", true);
          }
      }
  }
  
  [MyAuthorizeAttribute]
  public class BaseMyController : Controller
  {
      protected virtual new MyPrincipal User
      {
          get { return HttpContext.User as MyPrincipal; }
      }
  }
  </code></pre>
  
  <p>Then in MVC controller,we can get the user information via <code>MyPrincipal</code> user property.</p>
  
  <p>However, when we start to use the same way in web api, we found that the web api has no <code>HttpContext</code> property and in <code>System.Web.Http.AuthorizeAttribute</code>, the method to be override accepts a <code>HttpActionContext</code> argument, it also has no <code>HttpContext</code> property or some where else we can set the <code>MyPrincipal</code> instance.</p>
  
  <p>I notice that the <code>System.Web.Http.AuthorizeAttribute</code> summary says </p>
  
  <blockquote>
    <p><em>Specifies the authorization filter that verifies the request's IPrincipal</em></p>
  </blockquote>
  
  <p>It seems that there is some other way to set the <code>IPrincipal</code> instance.</p>
  
  <p>I have no idea about it, any good advice? By the way, why does the asp.net web api controller have no <code>HttpContext</code>? Is there any design pattern about it? </p>
  
  <p>The related questions
  <a href="https://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal">ASP.NET MVC - Set custom IIdentity or IPrincipal</a></p>