CSRF Protection in AngularJS with Rails Backend
Problem
While you developing AngularJS app with Rails backend, the frequently asked question are:
Why Rails logged current user out after an ajax POST request?
CSRF
Digged in you’ll find there’s a
Can’t verify CSRF token authenticity
in your log, and raise error of
ActionController::InvalidAuthenticityToken
This is due to the protection we called CSRF to protect unauthorized attack.
To solve this problem, you can add these lines (back?) to your application.js:
//= require jquery
//= require jquery_ujs
But what if you don’t want jQuery dependencies for AngularJS projects?
Here’s my solution
Use ng-rails-csrf gem.
Why
It’s simple and shipped with best practices, requires zero configuration and maintained by open source community. It also supports turbolinks out of box.
Installation (From README.md)
Add this line to your application’s Gemfile:
gem ‘ng-rails-csrf’
And then execute:
bundle install
In your module definition, include the ng-rails-csrf module
var myAwesomeModule= angular.module( ‘myAwesomeModule’, [ ‘ngResource’, ‘ng-rails-csrf’ ] ).
Then, require it in your application.js. The following line should go before any module, but must go after angular (since it’s an angular module).
//= require angular
//= require ng-rails-csrf
Great! Get rid of jQuery dependency here!
What’s more…
But, I do want my sign out link to work. I really need jquery_ujs to make it work:
ul
li= link_to ‘Sign Out’, destroy_user_session_path, method: :delete