我有兴趣了解人们在为其 Web 应用程序构建 RESTful(或准 RESTful)API 时采取的方法。
一个实际的例子:
假设您有一个传统的基于浏览器的 Web 应用程序,它对所有表单都使用 CSRF 保护。浏览器中显示的每个表单中都包含带有 CSRF 保护令牌的隐藏输入。提交表单后,如果此输入与令牌的服务器端版本不匹配,则该表单被视为无效。
现在假设您想要将 Web 应用程序公开为 API(可能使用 JSON 而不是 HTML)。传统上,在发布 API 时,我认为事务是单方面的(这意味着 API 使用者基于已发布的 API 构建请求,而不是首先请求表单,然后使用返回的表单构建请求)。
当诸如 CSRF 保护因素加入时,“单边”方法就会失效。CSRF 保护令牌需要包含在 API 使用者发送的任何 POSTS/PUTS/DELETES 中。
我一直在思考如何最好地解决这个问题。每次需要进行 API 调用时请求一个表单似乎非常尴尬(尤其是在处理异步操作时),但我自己想到的所有其他替代方案似乎都击败了 CSRF 保护(或者至少在其中打孔) ),这是不可接受的。
你们中有人对此有见解吗?
谢谢。
(并不是说它应该太重要,因为问题是概念性的和平台无关的,但我正在处理传统的 LAMP 堆栈并使用 Symfony 1.4 作为我的应用程序框架。我的目标是发布一个 JSON 格式的 Web API,允许开发人员使移动/桌面应用程序能够与现有的 Web 应用程序很好地配合。)
I'm interested in hearing what approaches people have taken when building a RESTful (or quasi-RESTful) API for their web applications.
A practical example:
Say you have a traditional browser-based web application which uses CSRF protection on all forms. A hidden input with a CSRF protection token is included in each form presented in the browser. Upon submission of the form, if this input does not match the server-side version of token, the form is considered invalid.
Now say you want to expose the web application as an API (perhaps using JSON instead of HTML). Traditionally when publishing an API, I've considered transactions to be unilateral (meaning the API consumer builds the request based on the published API instead of first requesting a form and then building a request using the returned form).
The "unilateral" approach breaks down when things like CSRF protection factor in. The CSRF protection token needs to be included in any POSTS/PUTS/DELETES sent by the API consumer.
I've been trying to think of how best to address this. Requesting a form each time an API call needs to be made seems very awkward (especially when dealing with asynchronous operations), but all other alternatives I've thought of on my own seem to defeat the CSRF protection (or at least punch holes in it), which is unacceptable.
Do any of you have insight into this?
Thanks.
(Not that it should matter too much, as the issue is conceptual and platform agnostic, but I'm dealing with a traditional LAMP stack and use Symfony 1.4 as my application framework. My goal is to publish a JSON-format web API allowing developers to make mobile/desktop apps that play nice with an existing web application.)
发布评论
评论(1)
REST 与身份验证(即基本身份验证)配合得很好,因此请尝试使用用户站点的用户名和特定于绑定到该用户的应用程序的密码——有时称为 API 密钥的技术。 FriendFeed 的 API 正在执行的操作请参阅文档。
有几点需要注意:
REST goes quite well with authentication (i.e. Basic Authentication), so try using username of your user site's and password specific to an application bound to that user -- technique sometimes called API keys. Something that FriendFeed's API is doing see the documentation.
Few notes tough: