How to Set Up Simple Http Authentication for a Ruby on Rails App on Heroku

Is there a way to set up simple http authentication for a Ruby on Rails app on heroku?

Absolutely. The simplest solution is to just put something in your application controller that uses Rails's built in basic auth support (see here: http://railscasts.com/episodes/82-http-basic-authentication) and just wrap it in a conditional for your Rails.env. Note that on Heroku, by default the RAILS_ENV is set to production, but you can change this for your non-production apps using heroku config (http://docs.heroku.com/config-vars).

You could also consider installing some roadblock-style Rack middleware, but I'd just go with the above.

HTTP basic auth for Rack::Static app on Heroku

use Rack::Static, 
:urls => ["/stylesheets", "/images", "/javascripts"],
:root => "public"

#SOLUTION:
use Rack::Auth::Basic, "Restricted Area" do |username, password|
[username, password] == ['admin', 'admin']
end

run lambda { |env|
[
200,
{
'Content-Type' => 'text/html',
'Cache-Control' => 'public, max-age=86400'
},
File.open('public/index.html', File::RDONLY)
]
}

Doing a Http basic authentication in rails

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"])

How can I keep my Heroku application private?

My cheap solution has been implementing a before_filter to request an HTTP authentication before every action is executed.

This solution works well along other authentication layers – Devise or others.

USERS = { "user" => "secret" }

before_filter :authenticate

def authenticate
authenticate_or_request_with_http_digest("Application") do |name|
USERS[name]
end
end

Whenever other peers land at yourdomain.heroku.com, they are asked for HTTP authentication, later for other authentication if in place.

How do you configure a Heroku Rack/Rails app to authenticate the client certificate of an incoming request?

In short, you can't, since we don't have control of the http layer (thin or the routing mesh) in the stack.

An alternative is to authenticate one's requests simply using a custom request header.



Related Topics



Leave a reply



Submit