开发者

using htaccess password protection on rails?

开发者 https://www.devze.com 2022-12-29 13:30 出处:网络
I want the /admin route on my rails app 开发者_开发知识库to be protected by using .htaccess password files - is this possible?Rails has a built-in helper for this, you could place this in your applica

I want the /admin route on my rails app 开发者_开发知识库to be protected by using .htaccess password files - is this possible?


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

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

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.

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号