Rack::Auth::Basic
からuse
を入力すると、実際にリクエスト処理チェーンに挿入されます。それはすべての要求を認証しようとします。選択的に使用するには、特定のパスでのみ、対応する要求エンドポイント(アクション)でauthを実行する必要があります。以下のような何か -
# helpers in ApplicationController
def authorized?
@auth = Rack::Auth::Basic::Request.new(request.env)
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['username', 'password']
end
def username(username)
@auth.credentials[0]
end
# action in PostsController
def index
if authorized?(params[:id]) && username == "admin"
# protected stuff
else
render :text => "unauthorized"
end
end
参考:Sinatra doc
認証のこの種は、完全なユーザー・アカウントとセッションベースのアプローチを行うことによって、より良い処理することができますが。レール3.1またはdeviseのチェックアウトhas_secure_password