gpt4 book ai didi

ruby - Rack::Auth 是否与基本 HTTP 身份验证相同?

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:39 28 4
gpt4 key购买 nike

我正在使用来自 Sinatra docs 的以下代码限制对我的 Sinatra 应用程序设置页面的访问.

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 基本身份验证相同?

还有什么我可以或应该做的来保护它吗?

最佳答案

是的,是一样的。您可以使用 Digest 身份验证,或者如果您想坚持使用 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/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

./controller/admin.rb

class App < Sinatra::Application

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

end

./views/admin/index.haml

%h1 Admin
%p Welcome!

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

运行应用

关于ruby - Rack::Auth 是否与基本 HTTP 身份验证相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7202646/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com