发出 PUT/POST/DELETE 跨域请求的 JSONP 问题
我创建了一个支持 GET/POST/PUT/DELETE 请求的 RESTful API。现在我希望我的API有一个Javascript客户端库,我想使用JSONP来绕过跨域策略。这可行,但当然仅适用于 GET 请求。
所以我开始思考如何实现这样一个东西,同时尝试让它使用起来更加轻松。
我想编辑我的 API 实现并检查每个 HTTP 请求。如果它是 JSONP 请求(它在查询字符串中有一个“回调”参数),我会强制每个 API 方法由 GET 请求执行,即使它应该由其他方法(如 POST 或 DELETE)调用。
这不是解决问题的 RESTful 方法,但它确实有效。你怎么认为?
也许另一个解决方案是动态生成 IFrame 来发送非 GET 请求。有什么建议吗?
I've created a RESTful API that supports GET/POST/PUT/DELETE requests. Now I want my API to have a Javascript client library, and I thought to use JSONP to bypass the cross-domain policy. That works, but of course only for GET requests.
So I started thinking how to implement such a thing and at the same time trying to make it painless to use.
I thought to edit my API implementation and check every HTTP request. If it's a JSONP requests (it has a "callback" parameter in the querystring) I force every API method to be executed by a GET request, even if it should be called by other methods like POST or DELETE.
This is not a RESTful approach to the problem, but it works. What do you think?
Maybe another solution could be to dynamically generate an IFrame to send non-GET requests. Any tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一个非常相似的问题的一些相关要点...
JSONP 与真正的 REST 的含义
跨域限制的存在是有原因的;-)
Jsonp 允许您公开 API 的有限、安全、只读视图以进行跨域访问 - 如果您破坏了这一点,那么您可能会打开一个巨大的安全漏洞- 恶意网站只需包含一个带有指向 API 正确部分的 href 的图像即可对您的 API 进行破坏性调用
让您的 Web 应用程序公开通过 iframe 访问的某些功能,其中所有 ajax 都发生在您的 Web 应用程序域的上下文中更安全的选择。即使如此,您仍然需要考虑 CSRF。 (查看 Django 博客上的 Django 最新安全公告作为一个主要示例 - 从本周发布的版本开始,默认情况下对 Django Web 应用程序的所有 javascript 调用都必须经过 CSRF 验证)
There's some relevant points on a pretty similar question here...
JSONP Implications with true REST
The cross-domain restrictions are there for a reason ;-)
Jsonp allows you to expose a limited, safe, read-only view of the API to cross domain access - if you subvert that then you're potentially opening up a huge security hole - malicious websites can make destructive calls to your API simply by including an image with an href pointing to the right part of the API
Having your webapp expose certain functionality accessed through iframes, where all the ajax occurs within the context of your webapp's domain is definitely the safer choice. Even then you still need to take CSRF into consideration. (Take a look at Django's latest security announcement on the Django blog for a prime example - as of a release this week all javascript calls to a Django webapp must be CSRF validated by default)
Iframe hack 在最近的浏览器上不再起作用,不要再使用它(来源:http://jquery-howto.blogspot.de/2013/09/jquery-cross-domain-ajax-request.html)
The Iframe hack is not working anymore on recent browsers, do not use it anymore (source : http://jquery-howto.blogspot.de/2013/09/jquery-cross-domain-ajax-request.html)