title: MVC.NET: registering message handler fails for claims based authorization
body: <p>
  Hello, I have built an Authorization Handler in order to intercept all requests of my MVC.NET v4 Application (Using .NET 4.5).</p>
  
  <p>The Handler is registered in Global.asax.cs, in WebAPIConfig.cs, for both global and path based route configurations and I have done all of the steps detailed in ASP.NET Web API Security book py Apress.</p>
  
  <p>What is the proper way to register an Auth Handler for an MVC.NET Web Application?</p>
  
  <p><strong>WebAPIConfig.cs</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>public static class WebApiConfig
  {
     public static void Register(HttpConfiguration config)
     {           
         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional },
             constraints: null,
             handler: new AuthHandler()
         );
         config.MessageHandlers.Add(new AuthHandler());
         // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable&lt;T&gt; return type.
         // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
         // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
         //config.EnableQuerySupport();
     }
  }
  </code></pre>
  
  <p><strong>AuthHandler.cs</strong>
  </p>
  
  <pre class="lang-cs prettyprint-override"><code>public class AuthHandler : DelegatingHandler
   {
     protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {     
         var claims = new List&lt;Claim&gt;() {new Claim(ClaimTypes.Name, "ghoil")};
  
         var id = new ClaimsIdentity(claims, "dummy");
         var principal = new ClaimsPrincipal(new[] { id });
  
         var config = new IdentityConfiguration();
         var newPrincipal = config.ClaimsAuthenticationManager.Authenticate(request.RequestUri.ToString(), principal);
  
         Thread.CurrentPrincipal = newPrincipal;
  
         if (HttpContext.Current != null)
             HttpContext.Current.User = newPrincipal;
  
         return await base.SendAsync(request, cancellationToken);          
     }
  }
  </code></pre>