如何将 Auth::Basic 添加到简单的 Rack 应用程序

how to add Auth::Basic to simple Rack application

如何添加这个

use Rack::Auth::Basic do |username, password|
  username == 'pippo' && password == 'pluto'
end

至此

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end


run HelloWorld.new

我有这个简单的 Rack 应用程序,我需要添加 Auth::Basic。

谢谢

您需要使用Rack::Builder来组成机架应用程序堆栈。

示例:

# app.ru
require 'rack'

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end

app = Rack::Builder.new do
  use Rack::Auth::Basic do |username, password|
    username == 'pippo' && password == 'pluto'
  end

  map '/' do
    run HelloWorld.new
  end
end

run app

并启动它:

$ rackup app.ru