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?
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.
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"])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With