Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 protect_from_forgery not working correctly?

I am using Rails 3.0.2 which has protect_from_forgery by default in application_controller.rb.

I wanted to trigger an InvalidAuthenticityToken.
To do this I have added this javascript to my page:

$('input[name=authenticity_token]').val('aaa')

Checking the DOM with Firebug I see the authenticity_token hidden field is correctly updated.

If I submit the form and check the log from the server I see the relative parameter is correctly set to 'aaa'. I would expect to get a InvalidAuthenticityToken while the request is processed as it was correct!

How is this possible?

like image 681
Diego Avatar asked May 22 '11 19:05

Diego


People also ask

What does Protect_from_forgery do in Rails?

Rails includes a built-in mechanism for preventing CSRF, protect_from_forgery , which is included by default in the application_controller. rb controller when generating new applications. This protect_from_forgery method leverages magic to ensure that your application is protected from hackers!

How does Rails prevent CSRF?

Briefly, Cross-Site Request Forgery (CSRF) is an attack that allows a malicious user to spoof legitimate requests to your server, masquerading as an authenticated user. Rails protects against this kind of attack by generating unique tokens and validating their authenticity with each submission.

What is Verify_authenticity_token?

verify_authenticity_token() private. The actual before_action that is used to verify the CSRF token.


1 Answers

The documentation for the authenticity token/csrf behavior is out of date. The InvalidAuthenticityToken exception is no longer thrown in these cases, instead your session is just reset. If you would like to handle this differently (or the old way) you can define your own behavior in handle_unverified_request on your controller.

like image 181
jdeseno Avatar answered Oct 21 '22 12:10

jdeseno