基于权限从WebApi端点进行上下文序列化

Bro*_*ski 8 rest serialization data-security asp.net-web-api

我正在使用Asp.Net Web Api.我希望能够根据连接的客户端访问权限过滤掉响应对象上的某些字段.

例:

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

    string Wobble { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

返回数据时,Wibble只有当前用户上下文可以满足"Uberlord"的值时,才应返回该字段.

我正在探索三种途径,但我没有一个有效的解决方案:

  1. 自定义WebApi MediaTypeFormatter.
  2. 自定义json.net IContractResolver.
  3. 某种用于操纵响应对象的控制器的AOP包装器

我的问题是:

  • 自定义格式化程序不是正确的位置,但可能是唯一的选择.
  • 自定义json序列化程序无法访问当前上下文,所以我必须解决这个问题.
  • 使用前两个选项,您需要针对每种响应格式,json,xml,某些自定义格式等进行特定实现.这意味着如果支持其他响应类型,则需要自定义格式化程序/序列化程序来防止敏感数据泄漏.
  • AOP控制器包装器需要大量反射.

另一个好处是使用相同的机制从入站请求对象的字段中去除值.

我错过了一个明显的钩子吗?这是通过另一种方式解决的吗?

Bro*_*ski 4

实际上比我最初想象的要简单得多。我没有意识到的是,可以用来操纵Web Api PipelineDelegatingHandler中的响应和请求。

ASP.NET Web API 消息的生命周期

委托处理程序


委托处理程序是消息管道中的一个扩展点,允许您在将请求传递到管道的其余部分之前对其进行处理。返回的响应消息也必须通过委托处理程序,因此任何响应也可以在此扩展点上进行监视/过滤/更新。

如果需要,委托处理程序也可以绕过管道的其余部分并发送回 Http 响应本身。

例子

下面是 DelegatingHandler 的示例实现,它可以操作响应对象或完全替换它。

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;
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

有关如何实现委托处理程序并将其添加到管道的 Microsoft 文章。ASP.NET Web API 中的 HTTP 消息处理程序