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:<
# 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
When connecting to HTTP endpoints protected by basic HTTP authentication I usually use HTTParty. HTTParty is simple wrapper for lower Ruby STD classes like net/http.
Example usage of HTTParty with basic auth.
class Delicious
include HTTParty
base_uri 'https://api.del.icio.us/v1'
def initialize(u, p)
@auth = {username: u, password: p}
end
def recent options={}
options.merge!({basic_auth: @auth})
self.class.get('/posts/recent', options)
end
end
delicious = Delicious.new("<username>", "<password>")
pp delicious.recent #=> list of recent elements
Check for more examples on GitHub.