Doing a Http basic authentication in rails
In Ruby on Rails 4 you can easily apply basic HTTP Authentication site wide or per controller depending on the context.
For example, if you need site wide authentication:
class ApplicationController < ActionController::Base
http_basic_authenticate_with name: "admin", password: "hunter2"
end
Or on a per controller basis:
class CarsController < ApplicationController
http_basic_authenticate_with name: "admin", password: "hunter2"
end
Write the below code, in the controller which you want to restrict using http basic authentication
class ApplicationController < ActionController::Base
http_basic_authenticate_with :name => "user", :password => "password"
end
Making a request with open-uri would look like this:
require 'open-uri'
open("http://www.your-website.net/",
http_basic_authentication: ["user", "password"])
# 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 then you just need to export your environment variable with the user:password for example:
export HTTP_AUTH=user:pass
if you are using heroku.com:
heroku config:set HTTP_AUTH=user:pass
I upvoted @Nishant's answer but wanted to add another tidbit. You can always set filters so it only applies to certain controller actions by passing only
or except
like so:
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", only: [:admin, :new, :edit, :destroy]
or
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", except: [:show]
Very helpful in many instances.