Last Updated: February 25, 2016
·
1.219K
· banafederico

XSRF protection using Rails and AngularJS

class ApplicationController < ActionController::Base
  protect_from_forgery

  # Manually check authenticity using the X-XSRF-TOKEN.
  # AngularJS will automatically send this header if the cookie
  # set below is found.
  skip_before_filter :verify_authenticity_token, 
                     :if => Proc.new { |app|
                       app.request.headers['X-XSRF-TOKEN'] == form_authenticity_token
                     }

   before_filter :set_xsrf_cookie

   # With this cookie we are making AngularJS send a X-XSRF-TOKEN
   # header with every subsequent request. We'll use this header to
   # manually check user authenticity.
   def set_xsrf_cookie
     cookies['XSRF-TOKEN'] = {
       value: form_authenticity_token,
       expires: 1.hour.from_now
     }
   end
 end