Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a Http basic authentication in rails

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:

def authString = "${key}:".getBytes().encodeBase64().toString() def conn = "http://something.net".toURL().openConnection() conn.setRequestProperty("Authorization", "Basic ${authString}") 

Can the same be done with rails?

like image 734
sriram Avatar asked Jan 17 '13 08:01

sriram


People also ask

Can HTTP can control basic authentication?

HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header.


2 Answers

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"]) 
like image 117
Nishant Avatar answered Oct 05 '22 23:10

Nishant


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 
like image 26
sergserg Avatar answered Oct 06 '22 01:10

sergserg