仅在一个页面上显示Sinatra Basic HTTP Auth

时间:2013-01-20 23:15:50

标签: ruby sinatra

我是否知道如何仅在模块化Sinatra应用程序的一个页面上显示Sinatra HTTP auth?

3 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分: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

或者您可以使用a filter

  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-contrib gem中的Sinatra::Namespace(可能更多一些高级用法,但我会使用它,因为我发现这是一种很好的做事方式)受保护的页面现在位于“/ 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

答案 2 :(得分: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 它的使用非常简单