How do I exclude a path from requiring basic auth in Sinatra

无人久伴 提交于 2019-12-06 03:59:15

问题


I'm writing a smallish web service in Ruby using Sinatra. Access to pretty much everything is controlled using http basic auth (over https in production).

There is one particular directory that I want to exclude from requiring authorization. Is there an easy way to do this?


回答1:


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!" }


来源:https://stackoverflow.com/questions/2062801/how-do-i-exclude-a-path-from-requiring-basic-auth-in-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!