rest - 基于权限的 WebApi 端点的上下文序列化

标签 rest serialization asp.net-web-api data-security

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

例子:

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

    string Wobble { get; set; }
}

返回数据时归档Wibble仅当当前用户上下文可以满足“Uberlord”的值时才应返回。

我正在探索三种途径,但我没有找到可行的解决方案:
  • 自定义 WebApi MediaTypeFormatter。
  • 自定义 json.net IContractResolver。
  • 某种类型的 AOP 包装器,用于操纵响应对象的 Controller

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

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

    我错过了一个明显的钩子(Hook)吗?这是否已通过其他方式解决?

    最佳答案

    它实际上比我最初想象的要简单得多。我没有意识到 DelegatingHandler 可用于操纵响应以及 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.


    例子
    这是 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;
                });
        }
    }
    
    有关如何实现委托(delegate)处理程序并将其添加到管道的 Microsoft 文章。 HTTP Message Handlers in ASP.NET Web API

    关于rest - 基于权限的 WebApi 端点的上下文序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172076/

    相关文章:

    C++:缓存 JSON 而不是对象会减少内存消耗吗?

    c - C (C89) 中十进制数的有效磁盘存储

    c# - ASP.NET 如何在 Web API 中读取多部分表单数据?

    c# - 我不能在此处将我的 ADO.NET 实体模型实例包装在 using 语句中吗?

    java - Rest API 身份验证失败 - Jenkins

    java - 需要实现自定义 Fitnesse 响应器

    node.js - Jasper Rest API,运行报告

    c# - 如何比较两个 .NET 对象图的差异?

    Spring Data Rest - PUT 不适用于关联的引用类型?

    asp.net - Azure Functions 中的 DI