Do I need CSRF token for API?

Do I need CSRF token for API?

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. CSRF attacks rely on cookies being implicitly sent with all requests to a particular domain.

How do you prevent CSRF attacks in REST API?

How to prevent CSRF in a RESTful application?

  1. Check referer – RESTful but unreliable.
  2. insert token into form and store the token in the server session – not really RESTful.
  3. cryptic one time URIs – not RESTful for the same reason as tokens.

How does CSRF token prevent CSRF?

CSRF tokens can prevent CSRF attacks by making it impossible for an attacker to construct a fully valid HTTP request suitable for feeding to a victim user.

Can a CSRF token be transmitted using cookies?

CSRF tokens should not be transmitted using cookies. The CSRF token can be added through hidden fields, headers, and can be used with forms, and AJAX calls. Make sure that the token is not leaked in the server logs, or in the URL.

When do you need to use CSRF protection?

CSRF attacks depend upon this behavior. If you do not use cookies, and don’t rely on cookies for authentication, then there is absolutely no room for CSRF attacks, and no reason to put in CSRF protection. If you have cookies, especially if you use them for authentication, then you need CSRF protection.

How to send CSRF tokens with Ajax request?

If you enable this and need to send the value of the CSRF token with an AJAX request, your JavaScript must pull the value from a hidden CSRF token form input on the page instead of from the cookie.

Is it possible to CSRF a REST API endpoint?

Rest API endpoints have a very important difference from other requests: they are specifically stateless, and should never accept/use data from either a cookie or session. If that is how you define “REST API”, then no CSRF is possible.