Per-Route Claims Transformation in ASP.NET Web API

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)

PerRouteClaimsTransform

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.

This entry was posted in IdentityModel, WebAPI. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s