Christoffer
Christoffer

Reputation: 2411

Rails: Test against and handle ActionController::InvalidAuthenticityToken

I have a Rails web app with some forms users can use to comment etc. They are frequently being used by spammers trying to create spam comments. Nothing new about that.

Sometimes I get CSRF-hack attempts which causes an ActionController::InvalidAuthenticityToken exception. This happens quite a lot and I would like to rescue and send the user/bot to a "You failed to comment"-page.

This has turned out to be a tricky exception to catch though since I can't recreate the error myself. I first put a rescue in the #create when the model (created by the form) was to be saved but it doesn't catch the exception. In order to do so I consider having it cover the entire controller section but that seems over the top.

My two questions:

  1. Is there a way to re-create an ActionController::InvalidAuthenticityToken error by myself, so I can test it?

  2. When is the exception raised? During .save? On Comment.new? Basically, where should I put my begin/rescue?

Thanks!

Upvotes: 1

Views: 1405

Answers (1)

jameswilliamiii
jameswilliamiii

Reputation: 878

You can rescue from this exception in your controller. One way you can set this up is to add a rescue in your ApplicationController.

class ApplicationController < ActionController::Base    
  rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_auth_token

  private

  def record_not_found
    render :text => "You failed to comment", :status => 422
  end

end

You could also just capture the exception locally in your controller action.

def create
  begin
    # Create your comment
  rescue ActionController::InvalidAuthenticityToken
    # Render your last view with some error text.
  end
end

You can add raise ActionController::InvalidAuthenticityToken inside your action if you want to test it out.

Upvotes: 5

Related Questions