Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do CSRF attacks apply to API's?

I'm writing a Django RESTful API to back an iOS application, and I keep running into Django's CSRF protections whenever I write methods to deal with POST requests.

My understanding is that cookies managed by iOS are not shared by applications, meaning that my session cookies are safe, and no other application can ride on them. Is this true? If so, can I just mark all my API functions as CSRF-exempt?

like image 487
alexgolec Avatar asked May 24 '12 16:05

alexgolec


People also ask

Is CSRF possible on API?

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.

How do you prevent CSRF attacks in REST API?

Enable CSRF Protection With REST API 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.

What is CSRF in web API?

Cross-Site Request Forgery (CSRF) is an attack where a malicious site sends a request to a vulnerable site where the user is currently logged in. Here is an example of a CSRF attack: A user logs into www.example.com using forms authentication. The server authenticates the user.


2 Answers

That's not the purpose of CSRF protection. CSRF protection is to prevent direct posting of data to your site. In other words, the client must actually post through an approved path, i.e. view the form page, fill it out, submit the data.

An API pretty much precludes CSRF, because its entire purpose is generally to allow 3rd-party entities to access and manipulate data on your site (the "cross-site" in CSRF). So, yes, I think as a rule any API view should be CSRF exempt. However, you should still follow best practices and protect every API-endpoint that actually makes a change with some form of authentication, such as OAuth.

like image 123
Chris Pratt Avatar answered Sep 30 '22 18:09

Chris Pratt


CSRF attacks rely on cookies being implicitly sent with all requests to a particular domain. If your API endpoints do not allow cookie-based authentication, you should be good.

Even if you do use cookie-based authentication, your cookies are safe because iOS apps do not share cookies. However, unless you intentionally block web browsers by requiring an unusual user-agent header, another party could build a browser-based app that uses your API, and that app would be vulnerable to CSRF attacks if your API supports cookie-based authentication and doesn't apply CSRF protection.

like image 39
Nick Retallack Avatar answered Sep 30 '22 18:09

Nick Retallack