meijuh
meijuh

Reputation: 1077

Can CSRF happen in an API?

The web application framework we use has built-in support for handling Cross-site Request Forgery. This works well when data is posted with a browser to our webserver.

Currently we are developing an API in which an uploaded XML file is processed by the same application framework. Our API requires a unique token in the uploaded XML file for authentication. Since CSRF detection is enabled by default and the XML file does not contain a CSRF token we currently can not upload any data through this API.

However, we can quite easily disable CSRF detection, but is this safe?

A post here states -- quite boldly -- the following.

It is safe to remove csrf for API calls as the particular vulnerability can only be executed through a web browser.

Is this true? Can nothing similar to a CSRF attack happen through an API?

Upvotes: 4

Views: 750

Answers (2)

Pacerier
Pacerier

Reputation: 89613

It depends on what you mean by "disable CSRF detection".

Some pointers:

  • As long as you do validate the unique authentication token without fail, then there is no way the attacker can spoof a valid request without a valid token. This is straightforward.

  • "unique authentication token" here refers to something that is not sent by browsers automatically. (So no using stuff like HTTP Basic / Digest, Cookie header and etc.) It must be something unique that you (the API creator) came up with. This can be as easy as an additional Foobar:the_unique_token header.

  • Note that it is perfectly fine to identify the client based on the Cookie (or other tokens that browsers automatically send), but you must only allow entry when the unique token is provided.

As long as the attacker can spoof a valid request as long as he is able to guess/obtain the token (the_unique_token). So the token needs to be long, random, and single-use to be secure.

Upvotes: 0

kranthi117
kranthi117

Reputation: 628

That depends on how you use the API. Say if the website using the API is vulnerable to CSRF, that means the API is also vulnerable.

Wekipedia says that

CSRF exploits the trust that a site has in a user's browser.

To support API calls the server requires that the credentials be sent along with every request (or some equivalent like digest, security handle, hash). If the credentials are stored in application memory (like mobile app) API is not vulnerable to CSRF. But if the credentials are saved in a session or cookie the API is exposed to CSRF

Upvotes: 2

Related Questions