Monthly Archives: October 2011

WCF Web API–building an Authorize attribute

This is the thirteenth post on a series about the WCF Web API Preview 4 and 5.  Last post focused on custom operation parameter conversion. This post shows how to also use operation handlers to build something similar to ASP.NET MVC’s AuthorizeAttribute.

The goal is to have an attribute to annotate operations with authorization requirements, such as the illustrated by the following excerpt.

[ServiceContract]
class TheService
{
    [Authorize("Alice")]
    [WebGet(UriTemplate="")]
    HttpResponseMessage Get(...)
    {
		...
    }
}

Notice the [Authorize(“Alice”)] requiring the request’s user to have the “Alice” identity name.

WCF Web API doesn’t have MVC’s filters. However, it is possible to have a similar behavior using operation handlers. The following figure shows the overall idea.

Authorize

 

  • The EnableAuthorizeAttribute configuration extension method checks if the operation’s description contains any AuthorizeAttribute. If so, it adds a AuthorizeOperationHandler instance to the operation handler pipeline. This instance receives the user identity extracted from the AuthorizeAttribute.
  • The AuthorizeOperationHandler declares one input parameter, of type IPrincipal. During the request processing, this handler checks if the input principal has the same identity as the one extracted from the AuthorizeAttribute. If not, it terminates the request before it reaches the operation, by throwing an HttpResponseException.
  • Notice that the AuthorizeOperationHandler is completely decoupled from the authentication process. The authorization’s only dependency is on a principal injected as a parameter.
  • If the operation doesn’t have a AuthorizeAttribute, then no AuthorizationOperationHandler is added to its pipeline.
  • Notice that the end developer only has to annotate the operations with the AuthorizeAttribute and call the EnableAuthorizeAttribute over the configuration, to enable this behavior.

Finally, the (draft) code is available at https://github.com/pmhsfelix/WcfWebApi.Preview5.Explorations.