使用在轨道上htaccess的密码保护?密码保护、轨道、htaccess

2023-09-02 00:31:12 作者:小姐ぃ请留步

我要在我的Rails应用的/管理路由使用的.htaccess文件的密码进行保护 - 这可能

I want the /admin route on my rails app to be protected by using .htaccess password files - is this possible?

推荐答案

Rails有一个内置的帮手,这一点,你可以把这个应用程序中的控制器:

Rails has a built-in helper for this, you could place this in your application controller:

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

然后使用上的before_filter要保护(或只是把它贴在应用程序控制器来阻止整个网站)的任何控制器:

Then use a before_filter on any controllers you want to protect (or just stick it in the application controller to block the whole site):

before_filter :authenticate

此方法适用于Nginx的和Apache的,这是一个额外的好处。这不,但是,工作,如果你有充分的页面缓存启用 - 为游客从来没有碰到Rails堆栈;它不会踢

This method works on Nginx as well as Apache, which is an added bonus. It doesn't, however, work if you have full page caching enabled - as the visitor never hits the Rails stack; it won't kick in.

修改 刚才注意到您指定的/管理的路线。我所有的管理控制器继承从AdminController。你可以设置你的了,像这样:

Edit Just noticed that you specified the /admin route. All my admin controllers inherit from an AdminController. You could set yours up like so:

/app/controllers/admin/admin_controller.rb

/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

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

Then have all your controllers extend the admin controller, eg:

class Admin::ThingsController < Admin::AdminController

我的路线设置,如下所示:

My routes are setup like so:

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

希望有所帮助。

Hope that helps.