Rack :: Auth与基本HTTP身份验证相同吗?

时间:2011-08-26 09:25:59

标签: ruby http sinatra rack

我使用以下代码限制访问我的Sinatra应用的设置页面,Sinatra docs

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

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

before "/admin" do
  protected!
end

Rack :: Auth与.htaccess基本身份验证相同吗?

我能做或应该采取什么措施来保护它吗?

1 个答案:

答案 0 :(得分:3)

是的,它是一样的。你可以使用Digest auth,或者如果你想坚持使用Basic,你可以确保它使用SSL。

基本和摘要示例:

https://github.com/sinatra/sinatra-book-contrib/blob/master/middleware/rack_auth_basic_and_digest.md

使用基本示例应用的HTTPS:

./ config.ru

require 'rubygems'
require 'sinatra'
require 'haml'

require './app'

run App

./ app.rb

class App < Sinatra::Application

  configure do
    set :haml, :format => :html5
    set :root, File.dirname(__FILE__)
    # more config stuff, db, mailers, file storage etc...
  end

end

# HELPERS
require 'helpers/helpers'

# CONTROLLER
require 'controller/admin'

./助手/ helpers.rb

module Sinatra
  module RegexpRouteFilter
    def before_with_regexp(pattern, &blk)
      before do
        instance_eval(&blk) if request.path =~ pattern
      end
    end
  end

  register RegexpRouteFilter
end

class App < Sinatra::Application
  helpers do
    def protected!
      unless authorized?
        response['WWW-Authenticate'] = %(Basic realm="Testing HTTP Auth")
        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 == ['user', 'pass']
    end
  end

  before_with_regexp(/^\/admin/) do
    if settings.environment == :production
      unless (@env['HTTP_X_FORWARDED_PROTO'] || @env['rack.url_scheme']) == 'https'
        redirect "https://#{request.env['HTTP_HOST']}#{request.env["REQUEST_PATH"]}"
      end
    end
    protected!
  end
end

./控制器/ admin.rb

class App < Sinatra::Application

  get '/admin' do
    haml :"admin/index"
  end

end

./视图/管理/ index.haml

%h1 Admin
%p Welcome!

然后使用shotgun gem shotgun config.ru -p 4567

运行应用