How to add HTTP Basic Authentication to your Rails application

From time to time, it's good to deploy an early version of your application, so the client can take a look. With services like Heroku, it's super easy to deploy, but it's not good to leave the application visible to the public.

HTTP Basic Authentication to the rescue

Most of the PaaS providers abstract the web server from you, but even you have access to it, you can use Rails to setup basic authentication.

First, create a new concern in your controllers folder.

# app/controllers/concerns/http_auth_concern.rb
module HttpAuthConcern  
    extend ActiveSupport::Concern

    included do
        before_action :http_authenticate
    end

    def http_authenticate
        return true unless Rails.env == 'production'

        authenticate_or_request_with_http_basic do |username, password|
            username == 'username' && password == 'password'
        end
    end
end  

Now you just need to include this module in your application controller.

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

    include HttpAuthConcern

    # rest of your code

end  

If you don't need the environment check, you can skip everything and just use the http_basic_authenticate_with method, which takes options hash as an argument.

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

    http_basic_authenticate_with name: 'username', password: 'password'

end  

Once again, you can fork this gist to meet your needs.


comments powered by Disqus