ASP.NET Web API RTM includes support for per-route message handlers. This allows to do low level work very early in the pipeline (after global message handlers, before authorization filters). See here for some examples.
Per-route message handlers are also a good place in the pipeline to do claims transformation – especially when you want that transformation to only happen for specific controllers (otherwise you can use the global claims transformer that is already in Thinktecture.IdentityModel)
The handler code is very straightforward:
public class ClaimsTransformationHandler : DelegatingHandler
{
ClaimsAuthenticationManager _transfomer;
public ClaimsTransformationHandler(
ClaimsAuthenticationManager transformer,
HttpConfiguration configuration)
{
_transfomer = transformer;
InnerHandler = new HttpControllerDispatcher(configuration);
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var principal = _transfomer.Authenticate(
request.RequestUri.AbsoluteUri, ClaimsPrincipal.Current);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return base.SendAsync(request, cancellationToken);
}
}
Afterwards you register the handler with the route in question:
routes.MapHttpRoute(
name: “DefaultApiWithTransformation”,
routeTemplate: “api/resource”,
defaults: new { controller = “MyResource” } ,
constraints: null,
handler: new ClaimsTransformationHandler(
new MyClaimsTransformer(), GlobalConfiguration.Configuration)
);
The code is in Thinktecture.IdentityModel on GitHub – and in the Nuget package soon as well.