1

Hello, I have built an Authorization Handler in order to intercept all requests of my MVC.NET v4 Application (Using .NET 4.5).

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.

What is the proper way to register an Auth Handler for an MVC.NET Web Application?

WebAPIConfig.cs

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<T> 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();
   }
}

AuthHandler.cs

public class AuthHandler : DelegatingHandler
 {
   protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {     
       var claims = new List<Claim>() {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);          
   }
}
  • Welcome to SO! Is there a specific problem you are having with your project or are you looking for general best practices? Specific problems are easier to answer here as questions like 'what is the best way to do X?' can be subjective and difficult to answer. – Jeff Jul 10 '13 at 00:51
  • Thank you @Jeff, the problem in specific is that the Authorization Handler is not being called on each request. I need to know how to register the handler so it gets called at every request. – user2566537 Jul 10 '13 at 00:56
  • @user2566537: Is your auth handler being called for `/api/` requests? – Stephen Cleary Jul 10 '13 at 00:58
  • Does this post help? http://stackoverflow.com/questions/11535075/asp-net-mvc-4-web-api-authentication-with-membership-provider – Jeff Jul 10 '13 at 00:58
  • @StephenCleary nope, it just never gets called. Either with or without /api/ – user2566537 Jul 10 '13 at 20:55

0 Answers0