Sinatra HTTP基本身份验证获取用户并继续使用内部路由

时间:2014-02-04 00:16:58

标签: sinatra basic-authentication

我正在sinatra中构建一个小API。我需要对路由进行身份验证,并且我已经在执行以下操作(从文档中读取)

use Rack::Auth::Basic,"Protected Area" do |username, password|
   user = User.validate username, password
end

但我会有多个用户,所以我正在做这样的事情:

class Protected < Sinatra::Base
    use Rack::Auth::Basic,"Protected Area" do |username, password|
        User.validate username, password
    end

    get '/users' do
        content_type :json
        #I want to return the user who was authenticated
    end    
end

如果用户确实存在于数据库中,则类方法Validate将返回用户;如果用户不存在,则返回false。但我不知道该怎么做才是如何从路径内访问该用户,例如get '/users' do

谢谢!

2 个答案:

答案 0 :(得分:3)

如果强制执行HTTP身份验证,则用户的名称在请求对象中可用,例如:

use Rack::Auth::Basic,"Protected Area" do |username, password|
  User.validate username, password
end

get '/' do
  user = request.env["REMOTE_USER"]
  "Hello, #{user}"
end

请注意,HTTP身份验证方案可能难以使用,您可能需要考虑使用sessions

答案 1 :(得分:0)

TITLE = "Password protected Area"
# TITLE = "The page is password protected, please provide a password. (any username is ok)" # alternative title

use Rack::Auth::Basic, TITLE do |_, password|
  password != File.read("./config/password.txt").strip
end
在我看来,

是最简单的解决方案。

它从文本文件中读取,您应该添加到您的gitignore