Rails 3 protect_from_forgery not working correctly?
Asked Answered
M

2

5

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?

Mercola answered 22/5, 2011 at 19:1 Comment(2)
you should accept the answer since it solved your pb.Burma
reset session is not enough to protect against CSRF. in rails 4, the default countermeasure is raising an exception, which is much more secure.Kofu
T
12

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.

Talbott answered 23/5, 2011 at 4:33 Comment(0)
H
1

I also believe you would have to reset the Authenticity token that resides in the meta tag of the html page that your form is in (I am assuming that you have the <%= csrf_meta_tag %> in there). Rails checks if either of the token in the form (that you changed in your javascript above) or the token in the meta tag of the html page match with Rails' expected authenticity token, and if ANY of them match, then your InvalidAuthenticityToken won't be triggered....

Hamill answered 2/4, 2012 at 23:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.