6

知道如何使 Sinatra HTTP 身份验证仅显示在模块化 Sinatra 应用程序的一页上吗?

4

3 回答 3

9

添加到@iain 答案,因为您已经询问了 HTTP 身份验证(我假设是基本身份验证)。

class MyApp < Sinatra::Base
  def authorized?
    @auth ||=  Rack::Auth::Basic::Request.new(request.env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ["CUSTOM_USERNAME","SECRET_PASSWORD"]
  end

  def protected!
    unless authorized?
      response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
      throw(:halt, [401, "Oops... we need your login name & password\n"])
    end
  end

  get "/protected_content" do
    protected!
    "in secure"
  end

  get "/" do
    "anyone can access"
  end
end
于 2013-01-21T10:13:59.850 回答
3

Vicky Chijwani 的评论是正确的,您应该提供更多信息(请注意!)但这是一个答案。

你可以通过几种方式做到这一点。如果我们假设您的身份验证方法被调用protected!

class MyApp < Sinatra::Base # assumed for all examples

  get "/only-this-page-has-auth" do
    protected!
    "Only admin allowed!"
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end
end

或者你可以使用过滤器

  before "/only-this-page-has-auth" do
    protected!
  end

  get "/only-this-page-has-auth" do
    "Only admin allowed!"
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end

或者,如果您打算Sinatra::Namespacesinatra-contrib gem中使用(可能更多的是高级用法,但我经常使用它,因为我发现它是一种很好的做事方式)并且受保护的页面现在将位于“ /admin/only-this-page-has-auth"

  namespace "/admin" do
    before do
      protected!
    end
    get "/only-this-page-has-auth" do
      "Only admin allowed!"
    end
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end
于 2013-01-21T08:14:31.897 回答
3

最好的方法是使用: https ://rubygems.org/gems/sinatra-basic-auth 文档很棒:

require "sinatra"
require "sinatra/basic_auth"

# Specify your authorization logic
authorize do |username, password|
  username == "john" && password == "doe"
end

# Set protected routes
protect do
  get "/admin" do
    "Restricted page that only admin can access"
  end
end

http://www.rubydoc.info/gems/sinatra-basic-auth/0.1.0 使用起来真的很简单

于 2015-01-14T12:46:16.820 回答