Authenticating Rails Engines with Devise

Devise is a very popular authentication engine for Rails. It comes packaged as a gem and takes care of a large amount of the boilerplate code you usually need to write around user management/authentication.

Today I was trying to add authentication a Rails engine we mount into our application. The standard code for adding authentication around controller actions is with an before filter.

class ApplicationController < ActionController::Base
  before_filter :authenticate_user!
end

As far as I can tell this doesn’t work for Rails engines since they use their own ApplicationController.

Luckily devise gives us a very easy way to add authentication at the route level, so just do the following where you are mounting your engine:

YourApp::Application.routes.draw do
  authenticate :user do
    mount Your::AwesomeEngine => '/your_engine'
  end
end

The user symbol corresponds to the method I’m calling in the before filter. So if you’re calling authentication_administrator! then you would substitute administrator for user.

Happy coding.