Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WARNING: Can't verify CSRF token authenticity in case of API development

I am right now developing web APIs with Ruby on Rails. When the Rails app receives POST request without any csrf token, the following error message shall happen. Because the app has no views.

WARNING: Can't verify CSRF token authenticity 

So my question is how can I escape csrf token check safely in this case?

Thank you very much in advance.

like image 873
diveintohacking Avatar asked Feb 23 '13 13:02

diveintohacking


People also ask

What are CSRF tokens?

A CSRF token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess. A CSRF secure application assigns a unique CSRF token for every user session.

What is CSRF token in rails?

Rails CSRF TokenThe server generates these tokens, links them to the user session, and stores them in the database. This token is then injected into any form presented to the client as a hidden field. When the client correctly submits the form for validation, it passes the token back to the server.

How does rails verify CSRF token?

A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.

What is Verify_authenticity_token?

verify_authenticity_token() private. The actual before_action that is used to verify the CSRF token. Don't override this directly.


2 Answers

You can do this by adding

skip_before_filter  :verify_authenticity_token 

to your controller. This way all incoming requests to the controller skips the :verify_authenticity_token filter.

like image 200
Kush Kella Avatar answered Sep 22 '22 08:09

Kush Kella


For rails 4 it should be

skip_before_action :verify_authenticity_token, only: [:one_or_two_actions_here] 

Note that you should avoid skipping verify_authenticity_token on all actions of your controller, instead use the option only to skip only where you have to. See the docs

like image 26
Bryan Dimas Avatar answered Sep 18 '22 08:09

Bryan Dimas