Last Updated: February 25, 2016
·
1.461K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

AngularJS pages are long-lived browser apps with the same script risk as a newer single-page app. Third-party code in the template can read forms and values rendered on the page.

Security insights from Cside