Hi I\'m from Grails background and new to Rails. I wish to do http basic authentication in rails.
I have a code in grails which does basic authentication like this:<
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
There is a great Rails Cast on this topic
http://railscasts.com/episodes/82-http-basic-authentication
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"])
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.
Above answers are correct, but it is better to not put the user and password in the source code.
Better have the password in environment variables for production (in the code is OK for development)
class YourController..
http_basic_authenticate_with name: ENV["HTTP_BASIC_AUTH_USER"], password: ENV["HTTP_BASIC_AUTH_PASSWORD"], if: -> { ENV['RAILS_ENV'] == 'production' }
http_basic_authenticate_with name: "user", password: "pass", if: -> { ENV['RAILS_ENV'] != 'production' }
For the latest rails version there is a ASCIIcast
that explains with steps the HTTP Basic Authentication.
The link goes here.
Side Note: Be warned that HTTP Basic Authentication transmits the username and password in clear text, so you should not use this method for applications where a higher level of security is required.