restserializationasp.net-web-apidata-security

Contextual serialization from WebApi endpoint based on permissions


I am using the Asp.Net Web Api. I would like to be able to filter out certain fields on the response objects based on the connected clients access rights.

Example:

class Foo
{
    [AccessFilter("Uberlord")]
    string Wibble { get; set; }

    string Wobble { get; set; }
}

When returning data the filed Wibble should only be returned if the current users context can satisfy the value of "Uberlord".

There are three avenues that I am exploring but I have not got a working solution:

  1. A custom WebApi MediaTypeFormatter.
  2. A custom json.net IContractResolver.
  3. Some sort of AOP wrapper for controllers that manipulates the response object

My issue with these are:

An additional bonus would be to strip out values from the fields on an inbound request object using the same mechanism.

Have I missed an obvious hook? Has this been solved by another way?


Solution

  • It was actually a lot simpler than I first thought. What I did not realise is that the DelegatingHandler can be used to manipulate the response as well as the request in the Web Api Pipeline.

    Lifecycle of an ASP.NET Web API Message

    Delegating Handler


    Delegating handlers are an extensibility point in the message pipeline allowing you to massage the Request before passing it on to the rest of the pipeline. The response message on its way back has to pass through the Delegating Handler as well, so any response can also be monitored/filtered/updated at this extensibility point.

    Delegating Handlers if required, can bypass the rest of the pipeline too and send back and Http Response themselves.

    Example

    Here is an example implementation of a DelegatingHandler that can either manipulate the response object or replace it altogether.

    public class ResponseDataFilterHandler : DelegatingHandler
    {
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;
    
                    //Manipulate content here
                    var content = response.Content as ObjectContent;
                    if (content != null && content.Value != null)
                    {
                        ((SomeObject)content.Value).SomeProperty = null;
                    }
    
                    //Or replace the content
                    response.Content = new ObjectContent(typeof(object), new object(), new JsonMediaTypeFormatter());
    
                    return response;
                });
        }
    }
    

    Microsoft article on how to implement a delegating handler and add it to the pipeline.HTTP Message Handlers in ASP.NET Web API