我如何仅在某些子域上使用http_basic_authenticate_with

问题描述 投票:1回答:2

我不会在管理子域上使用http_basic_authenticate_with。我尝试这样声明它

  http_basic_authenticate_with :name => ENV["WEBSITE_USERNAME"],
                               :password => ENV["WEBSITE_PASSWORD"],
                               :subdomain => 'admin',
                               :only => ['edit', 'destroy', 'new', 'index']

甚至尝试过

  http_basic_authenticate_with :name => ENV["WEBSITE_USERNAME"],
                               :password => ENV["WEBSITE_PASSWORD"],
                               :only => ['edit', 'destroy', 'new', 'index'] if request.subdomain == "admin" 

但是请求变量那时还不存在。

有人知道第一次访问admin子域时如何获得身份验证吗?

ruby-on-rails subdomain basic-authentication
2个回答
1
投票

在rails中很难找到关于这种身份验证的信息。我最终找到了一个名为

的方法
authenticate_or_request_with_http_basic

更多信息Here

我的结束代码是

before_action :index, :authenticate #this can be a filter as well should you need multiple actions

def authenticate
if request.subdomain == 'admin'
  authenticate_or_request_with_http_basic("Administration") do |user,pass| user == ENV["WEBSITE_USERNAME"] && pass = ENV["WEBSITE_PASSWORD"] end 
  end
end

0
投票

在较新版本的ruby&rails中,您可以使用lambda做到这一点

http_basic_authenticate_with name: ENV["HTTP_BASIC_AUTH_USER"], password: ENV["HTTP_BASIC_AUTH_PASSWORD"], if: -> { request.subdomain == "admin" }
© www.soinside.com 2019 - 2024. All rights reserved.