Skip to content

Instantly share code, notes, and snippets.

@tamouse
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/9d240638903d5680d0cc to your computer and use it in GitHub Desktop.
Save tamouse/9d240638903d5680d0cc to your computer and use it in GitHub Desktop.
Requiring HTTP authorization for a route.

How to use HTTP basic authorization in a controller.

FilterController uses a before_filter callback, calling authenticate_or_request_with_http_basic.

PostsController uses the http_basic_authentication_with callback.

require 'digest'
class FilterController < ApplicationController
before_filter :authenticate
def index
render text: "hello world, from the index!"
end
protected
def authenticate
user = authenticate_or_request_with_http_basic do |username, password|
username == 'foo' && password == 'bar'
end
@current_user = user
end
end
class PostsController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", except: :index
def index
render text: "Everyone can see me!"
end
def edit
render text: "I'm only accessible if you know the password"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment