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