【问题标题】:How to secure JSONP requests with Web API?如何使用 Web API 保护 JSONP 请求?
【发布时间】:2013-08-08 03:45:21
【问题描述】:

我正在使用这里的自定义 JSONP 格式化程序: http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

它适用于最新的 Web API。但是,我如何限制它不适用于我的所有 Web API 服务,而只有我放置 JSONP 属性或其他东西的那些。关于如何确保仅针对我选择的某些操作的任何想法?

【问题讨论】:

    标签: c# security asp.net-web-api jsonp


    【解决方案1】:

    如果您可以按照想要返回为 JSONP 的对象的类型来考虑,而不是操作,则可以像这样更改格式化程序以仅允许将某些类型序列化为 JSONP。

    public override bool CanWriteType(Type type)
    {
        // Check type here and return true only for the types you want to allow JSONP
        return true;
    }
    

    如果无法进行基于类型的过滤,另一种选择是不将格式化程序添加到格式化程序集合中并显式指定JsonpFormatter,就像这样,仅在您要返回 JSONP 的操作方法中。

    return new HttpResponseMessage()
    {
        Content = new ObjectContent<MyType>(anInstanceOfMyType, new JsonpFormatter())
    };
    

    然而,一个缺点是这将只返回 JSONP,而不管 conneg 出现什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 2018-06-04
      • 2015-02-20
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多