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.)
The CSRF token is required for any later REST API calls. The client must send a valid token with every API request. The token is sent in a custom request HTTP header. The name of the custom header is X-IBM-SPM-CSRF.
If our project requires CSRF protection, we can send the CSRF token with a cookie by using CookieCsrfTokenRepository in a custom WebSecurityConfigurerAdapter. After restarting the app, our requests receive HTTP errors, which means that CSRF protection is enabled.
Enabling cross-site request forgery (CSRF) protection is recommended when using REST APIs with cookies for authentication. If your REST API uses the WCToken or WCTrustedToken tokens for authentication, then additional CSRF protection is not required.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With