I recently started building a Rails driven web app and decided to use Devise for authentication. This would be pretty straight forward to implement but I planned to use AngularJS to power the front-end and decided to only use Rails as a JSON API.
Getting down to development on that path, I quickly ran into some problems structuring AngularJS to recognize Devise sessions. Thanks to some usefulexamples on GitHub I was able to get around those issues and get them to play nice. Here’s how:
Let’s first look at the main application.js file of my Angular app:
First, you’ll see I’m setting the request header with a CSRF token to make sure Rails doesn’t create a new session for every request that goes out. Second, I’m creating an interceptor which will basically intercept any 401 Unauthorized responses and direct them to the login page.
Next up let’s create a sessions controller (derived from Devise::SessionsController) which will give us some CRUD functionality through a JSON interface:
Now let’s create an AngularJS Session service which would interact with that controller:
That pretty much does it. Now if you call a service which tries to access any Rails controller with a “before_filter :authenticate_user!” in it, you will automatically be kicked out and prompted to login.