Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Protect From Forgery in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 797
    Comment on it

    The first concern for every application is its security, so rails by default provides a method protect_from_forgery, which is always present by default in your application, whenever you create a new application. i.e.

    1. class ApplicationController < ActionController::Base
    2. protect_from_forgery
    3. end

    So whenever you create a form in your rails application, in a hidden field, it always has a token, which gets sent by default so that, the rails application recognizes that the request has come from the same application. This protect_from_forgery verifies all requests except the GET and HEAD requests. Here we will discuss what options are available in this:


    1. Completely skipping:

    We can completely skip the protect_from_forgery, if our application is purely api based and we don't want any checks for forgery. It can be done by adding this line of code.

    1. skip_before_action :verify_authenticity_token
    2.  

     

    2. Customizing for specific actions:

    Like all the other rails filters, it also supports :only/:except options, so you can add the your methods in these blocks:

    1. class ApplicationController < ActionController::Base
    2. protect_from_forgery except: [:login, :signup]
    3.  
    4. ## or
    5.  
    6. protect_from_forgery only: [:edit, :show]
    7. end

     

    3. Providing blocks/conditions:

    It supports :if/:unless options too, so you can provide conditions here, regarding when you want to protect_from_forgery to work or not.

    1. protect_from_forgery if: :some_condition

     

    4. :with  

     It is used to set the method to handle unverified request.


    5. There are few methods available to handle the unverified requests, which are:

    a) exception: It is present by default with the rails application and raises ActionController::InvalidAuthenticityToken exception.

    b) reset_session: It resets all the available sessions.

    c) null_session:  It provides an empty session during request but doesn't reset it. It is used as default when :with option is not specified.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: