How to exclude a path from the required base auth in Sinatra

I am writing a small web service in Ruby using Sinatra. Access to almost everything is controlled using HTTP basic auth (more than https in production).

There is one specific directory that I want to exclude because of the need for authorization. Is there an easy way to do this?

+5
source share
1 answer
require 'sinatra'

helpers do
  def protected!
    unless authorized?
      response['WWW-Authenticate'] = %(Basic realm="Testing HTTP Auth")
      throw(:halt, [401, "Not authorized\n"])
    end
  end

  def authorized?
    @auth ||=  Rack::Auth::Basic::Request.new(request.env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['admin', 'admin']
  end
end

before { protected! unless request.path_info == "/public" }

get('/public') { "I'm public!" }
+11
source

All Articles