【Sinatra】ページ単位で Basic 認証を入れる
2022/08/21
Sinatra で Basic 認証を実装したい時は以下のような書き方で実現できる
use Rack::Auth::Basic do |username, password|
username == 'admin' && password == 'secret'
end
しかし、アプリケーション全体に認証が掛かってしまう
ページ単位で Basic 認証
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'sinatra'
gem 'puma'
end
helpers do
def protected!
return if authorized?
halt(401, 'Unauthorized.')
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
return unless @auth.provided? && @auth.basic? && @auth.credentials
@auth.credentials == ['takagi', 'thisispassword']
end
end
get '/' do
'Hello!'
end
get '/auth' do
protected!
'Authorized.'
end
Sinatra::Application.run!
$ curl localhost:4567
Hello!
$ curl localhost:4567/auth
Unauthorized.
$ curl --user takagi:thisispassword localhost:4567/auth
Authorized.