【问题标题】:using htaccess password protection on rails?在 Rails 上使用 htaccess 密码保护?
【发布时间】:2010-05-10 23:36:44
【问题描述】:

我希望使用 .htaccess 密码文件保护我的 rails 应用程序上的 /admin 路由 - 这可能吗?

【问题讨论】:

  • 属于 superuser.com,因为这是一个管理员问题。

标签: ruby-on-rails ruby .htaccess


【解决方案1】:

Rails 有一个内置的帮助器,你可以把它放在你的应用程序控制器中:

protected
  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == "test"
    end
  end

然后在您要保护的任何控制器上使用 before_filter(或将其粘贴在应用程序控制器中以阻止整个站点):

before_filter :authenticate

此方法适用于 Nginx 和 Apache,这是一个额外的好处。但是,如果您启用了整页缓存,它就不起作用——因为访问者永远不会碰到 Rails 堆栈;它不会启动。

编辑 刚刚注意到您指定了 /admin 路由。我所有的管理控制器都继承自 AdminController。你可以这样设置:

/app/controllers/admin/admin_controller.rb

class Admin::AdminController < ApplicationController
  before_filter :authenticate
  protected
    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == "test"
    end
  end
end

然后让您的所有控制器扩展管理控制器,例如:

class Admin::ThingsController < Admin::AdminController

我的路线是这样设置的:

map.namespace :admin do |admin|
    admin.resources :things
end

希望对您有所帮助。

【讨论】:

  • 这正是我想要的。谢谢!
  • 很好的解释!
猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多