LoginSignup
26
25

More than 5 years have passed since last update.

sinatraでBasic認証

Posted at

特定のアクションのみに認証をかける場合

helpers do
  def protected!
    unless authorized?
      response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
      throw(:halt, [401, "Not authorized\n"])
    end
  end

  def authorized?
    @auth ||=  Rack::Auth::Basic::Request.new(request.env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['changeme', 'changeme']
  end
end

get '/protected' do
  protected!
  "Protected page"
end
26
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25