开发者

Selectively allow some urls through Rack::Auth::Basic

开发者 https://www.devze.com 2023-03-07 01:10 出处:网络
I\'ve set up a blog that I\'d like to be minimally secured (i.e., I just want to keep out random people I don\'t know, I\'m not trying to implement NSA-like security measures). I\'m using toto with Ra

I've set up a blog that I'd like to be minimally secured (i.e., I just want to keep out random people I don't know, I'm not trying to implement NSA-like security measures). I'm using toto with Rack::Auth::Basic to "secure" the site. I'd li开发者_StackOverflowke to let through index.xml so that blog readers will be able to read the feed without dealing with password (and yes, I know that this is a big hole in my "security").

How do I let through this one url with Rack::Auth::Basic?

This is how I added basic auth to my site:

use Rack::Auth::Basic, "blog" do |username, password|
  [username, password] == ['generic', 'stupidanddumbpassword']
end


How about some good ol' fashioned inheritance? Rack::Auth::Basic is a simple rack app (source: https://github.com/rack/rack/blob/master/lib/rack/auth/basic.rb), so it's possible to override the #call method and skip authentication when the request path matches '/index.xml':

class BlogAuth < Rack::Auth::Basic

  def call(env)
    request = Rack::Request.new(env)
    case request.path
    when '/index.xml'
      @app.call(env)  # skip auth
    else
      super           # perform auth
    end
  end

end

use BlogAuth, "blog" do |username, password|
  [username, password] == ['generic', 'stupidanddumbpassword']
end

For more background on rack, check out: http://rack.rubyforge.org/doc/SPEC.html

I haven't tried @Iain's suggestion about Rack::URLMap, but it looks like it could also be a good option.


Thanks for the answer!

I used this solution too, but made a small change. because the current solution will probably result in a duplication of code if an app will require more then one path to be accessible, I changed the code to:

class AppBasicAuth < Rack::Auth::Basic
  def call(env)
    request = Rack::Request.new(env)
    allowed_paths = ['/api/v2/get_new.json']

    if allowed_paths.include? request.path
        @app.call(env)  # skip auth
    else
      super           # perform auth
    end
 end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消