HTTP基本认证对于一些(不是全部)控制器 [英] HTTP Basic Auth for some (not all) controllers

查看:188
本文介绍了HTTP基本认证对于一些(不是全部)控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rails 3.2。

Using Rails 3.2.

我有半打的控制器,并想要保护的部分(但不是全部)他们与 http_basic_authenticate_with

I have half a dozen controllers, and want to protect some (but not all) of them with http_basic_authenticate_with.

我不希望 http_basic_authenticate_with 来手动添加到每个控制器(我可以在将来添加其他控制器和忘记保护它!)。看来答案是把它放在 application_controller.rb :除了 ARG这将列出控制器,应的的保护。问题是,则:except子句希望的方法名称,而不是外部控制器模块名称,例如:

I don't want to manually add http_basic_authenticate_with to each controller (I could add another controller in the future and forget to protect it!). It seems the answer is to put it in application_controller.rb with an :except arg which would list the controllers that should not be protected. The problem is, the :except clause wants method names rather than external controller module names, e.g.:

http_basic_authenticate_with :name => 'xxx', :password => 'yyy', :except => :foo, :bar

于是我想:等一下,因为我已经在的routes.rb 分组受保护的控制器,让我们把它放在那里。所以,我在尝试的路线是:

So then I thought "Wait, since I already have the protected controllers grouped in routes.rb, let's put it there." So I tried this in my routes:

  scope "/billing" do
    http_basic_authenticate_with :name ...
    resources :foo, :bar ...
  end

但现在我得到

undefined method `http_basic_authenticate_with'

什么是接近最好的方法?

What's the best way to approach this?

推荐答案

做到这一点Rails的方式做的。

Do it the way Rails does it.

# rails/actionpack/lib/action_controller/metal/http_authentication.rb

def http_basic_authenticate_with(options = {})
  before_action(options.except(:name, :password, :realm)) do
    authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
      name == options[:name] && password == options[:password]
    end
  end
end

所有这一切 http_basic_authenticate_with 的作用是添加一个 before_action 。你可以很容易地做同样的自己:

All that http_basic_authenticate_with does is add a before_action. You can just as easily do the same yourself:

# application_controller.rb

before_action :http_basic_authenticate

def http_basic_authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == 'xxx' && password == 'yyy'
  end
end

这意味着你可以在这种行为是不希望的控制器使用 skip_before_action

# unprotected_controller.rb

skip_before_action :http_basic_authenticate

这篇关于HTTP基本认证对于一些(不是全部)控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆