Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the post method seem to be clearing my rails session data?

After the user has logged in and their username authenticated and saved in session[:user_name], when submitting a form with method="post" (using standard html) all session data is cleared and user is routed back to the login page. This does not happen if the method is set to get.

Post works when I use the rails "form_tag" which generates these additional lines:

<div style="margin: 0pt; padding: 0pt; display: inline;">
<input type="hidden" value="✓" name="utf8">
<input type="hidden" value="a_bunch_of_gibberish" name="authenticity_token">
</div>

What is happening?

like image 503
Lee Quarella Avatar asked Feb 22 '11 19:02

Lee Quarella


2 Answers

Are you using Rails 3.0.4? It sounds like it might be related to the CSRF fix.

If you need a fix specific to your needs, you can overwrite #handle_unverified_request in your controller. See https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/request_forgery_protection.rb.

Here's an example where this issue was with OmniAuth and OpenId. (See section 'CSRF Protection In Rails 3.0.4')

like image 129
monocle Avatar answered Oct 16 '22 08:10

monocle


This issue can also happen if you're creating your own html form.

If you're getting redirected without knowing why, it's because of "protect_from_forgery" in your ApplicationController

In order to allow your form to post, add the following code to it (or use form_tag, explanation below):

<form ... >
...
<%= hidden_field_tag "authenticity_token", form_authenticity_token %>
...
</form>

The reason the "form_tag" works is because form_tag generates the hidden field for you =)

like image 6
Abdo Avatar answered Oct 16 '22 08:10

Abdo