Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails test passing CSRF token only in get requests

I'm trying to unit-test my controllers, every test that uses the get request works fine, but the tests where I use other calls (delete in destroy, post in create and put in update) fail with a:

WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2.5ms

for example this is the test for destroy:

  test "should destroy blog" do
    assert_difference('Blog.count', -1) do
      delete :destroy, id: @blog
    end

    assert_redirected_to blogs_path
  end

which doesn't work

and this is the test for show, which works:

  test "should show blog" do
    get :show, id: @blog
    assert_response :success
  end

in the destroy test the devise authenticate_user! just redirects me to the sign_in page and the test fails.

like image 546
Don Giulio Avatar asked Aug 08 '14 16:08

Don Giulio


People also ask

How does rails verify CSRF token?

CSRF protection when plain vanilla Rails form is used On the server, Rails retrieves the token using params[:authenticity_token]. Rails checks if the token has been tampered with and if everything is fine then that request proceeds.

How CSRF token is passed?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.

How do I get CSRF token from response?

To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.

How does Ruby on 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.


1 Answers

Apparently it's a normal thing to disable the CSRF token in the test environment, I added:

  # Disable request forgery protection in test environment
  config.action_controller.allow_forgery_protection    = false

to my "/config/environments/test.rb" file and the current user was able to pass through.

like image 142
Don Giulio Avatar answered Sep 28 '22 23:09

Don Giulio