在rails上使用htaccess密码保护?

V_H*_*V_H 22 ruby .htaccess ruby-on-rails

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

rob*_*may 55

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

protected
  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == "test"
    end
  end
Run Code Online (Sandbox Code Playgroud)

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

before_filter :authenticate
Run Code Online (Sandbox Code Playgroud)

这种方法适用于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
Run Code Online (Sandbox Code Playgroud)

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

class Admin::ThingsController < Admin::AdminController
Run Code Online (Sandbox Code Playgroud)

我的路线设置如下:

map.namespace :admin do |admin|
    admin.resources :things
end
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.