Rails

How To Set CSRF With AngularJS And Rails

Posted by Weston Ganger on July 05, 2015

One common problem with AngularJS and Rails integration is getting the CSRF protection working.

You can implement it yourself as described below or add a gem that provides this angular_rails_csrf


# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  after_filter :set_csrf_cookie_for_ng

  protected

  # In Rails 4.2 and above
  def verified_request?
    super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
  end

  # In Rails 4.1 and below
  def verified_request?
    super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
  end

  private

  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end
end


Related External Links:


Posted in Rails and Tagged with angularjs rails csrf 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts