通过Rack :: Auth :: Basic选择性地允许一些URL

gui*_*ism 12 ruby rack

我已经建立了一个博客,我希望得到最低限度的安全保护(即,我只想保留我不知道的随机人员,我不想尝试实施类似NSA的安全措施).我正在使用托管与Rack :: Auth :: Basic来"保护"该网站.我想通过,index.xml以便博客读者能够在不处理密码的情况下阅读提要(是的,我知道这是我的"安全"中的一个大漏洞).

如何使用Rack :: Auth :: Basic通过这个URL?

这就是我将基本身份验证添加到我的网站的方式:

use Rack::Auth::Basic, "blog" do |username, password|
  [username, password] == ['generic', 'stupidanddumbpassword']
end
Run Code Online (Sandbox Code Playgroud)

ros*_*sta 19

一些好的'老式的继承怎么样?Rack :: Auth :: Basic是一个简单的机架应用程序(来源:https://github.com/rack/rack/blob/master/lib/rack/auth/basic.rb),因此可以覆盖#call方法并在请求路径与'/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
Run Code Online (Sandbox Code Playgroud)

有关机架上的更多背景信息,请访问:http://rack.rubyforge.org/doc/SPEC.html

我没有试过@Iain关于Rack :: URLMap的建议,但看起来它也是一个不错的选择.


guy*_*ler 6

谢谢你的回答!

我也使用过这个解决方案,但做了一个小改动.因为如果应用程序需要多个路径可访问,当前的解决方案可能会导致代码重复,我将代码更改为:

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
Run Code Online (Sandbox Code Playgroud)