Add basic http authentication in Rails

Add basic http authentication in Rails

Sometimes you want to add a basic security layer for your privated website or application in Rails, for those cases you can do it actually pretty easy and you just need to provide a user and password credentials in order access the Website/Web Application.

For example in my case I want to protect my website which is hosted on heroku.com.

The only method I needed to add was the following code in my ApplicationController:

# app/controllers/application_controller.rb
  before_filter :http_basic_auth

  def http_basic_auth
    if ENV['HTTP_AUTH'] =~ %r{(.+)\:(.+)}
      unless authenticate_with_http_basic { |user, password|  user == $1 && password == $2 }
        request_http_basic_authentication
      end
    end
  end

And you if you visit your website you are going to see nothing, that is because you need to export the HTTP_AUTH environment variable, if you are in development mode just export the variable with your desired values for example if your user and password are => test.

export HTTP_AUTH=test:test

If you are using heroku.com

heroku config:set HTTP_AUTH=test:test

Now when you visit your Application/Website in localhost:3000 a window prompt will ask you about the user credentials(test/test).

That’s it

H.

No Comments

Post A Comment