Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created October 13, 2008 01:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakajima/16483 to your computer and use it in GitHub Desktop.
Save nakajima/16483 to your computer and use it in GitHub Desktop.
Easy basic auth for Sinatra actions
=begin
Easy Basic Authentication for Sinatra actions.
USAGE
require 'rubygems'
require 'sinatra'
require 'sinatra-auth'
get '/' do
protect! :username => 'admin', :password => 'sekret'
"This is protected by basic auth"
end
=end
module Sinatra
module Authorization
class ProtectedAction
attr_reader :credentials, :context
def initialize(context, credentials={})
@credentials, @context = credentials, context
end
def check!
unauthorized! unless auth.provided?
bad_request! unless auth.basic?
unauthorized! unless authorize(*auth.credentials)
end
def remote_user
auth.username
end
private
def authorize(username, password)
credentials[:username] == username and credentials[:password] == password
end
def unauthorized!
context.header 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}")
throw :halt, [ 401, 'Authorization Required' ]
end
def bad_request!
throw :halt, [ 400, 'Bad Request' ]
end
def auth
@auth ||= Rack::Auth::Basic::Request.new(context.request.env)
end
end
module Helpers
def protect!(credentials={})
return if authorized?
guard = ProtectedAction.new(self, credentials)
guard.check!
request.env['REMOTE_USER'] = guard.remote_user
end
def authorized?
request.env['REMOTE_USER']
end
end
end
end
helpers do
include Sinatra::Authorization::Helpers
end
@bordanzig
Copy link

This works awesome, but you have a typo in ln43 context.header 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}")
It should be context.headers 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}") Just missing an "s"

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment