6

モジュラー Sinatra アプリケーションの 1 ページのみに Sinatra HTTP 認証を表示させる方法はありますか?

4

3 に答える 3

9

HTTP認証を要求したため、@iainの回答に追加します(基本認証を想定しています)。

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 に答える