使用authenticate_or_request_with_http_basic()时接收AbstractController :: DoubleRenderError

时间:2011-12-22 18:55:35

标签: ruby-on-rails-3.1 http-authentication actionview actioncontroller

当我在块的开头添加对authenticate_or_request_with_http_basic的调用时,我有一个工作的控制器动作。以下是无效的操作代码:

def index
  authenticate_or_request_with_http_basic do |username, password|
    username == "test1" and password == "test"
  end

  render layout: false, content_type: 'application/xml'
end

我在浏览器窗口中收到“AbstractController :: DoubleRenderError”错误响应,并显示以下消息:

  

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,每次操作最多一次。另请注意,重定向和呈现都不会终止执行操作,因此如果要在重定向后退出操作,则需要执行类似“redirect_to(...)并返回”的操作。

当我将“authenticate_or_request_with_http_basic”逻辑放在一个单独的操作中,然后配置一个before_filter来为索引操作运行它时,一切都很顺利。但是,我不会将此逻辑重用于索引以外的任何操作,我想知道为什么上面的代码不起作用。

解决方案

我能够在Tyler和RKB的帮助下找到解决方案。这是:

authenticated = authenticate_or_request_with_http_basic "Authentication Required" do |username, password|
  @user = User.find_by_username(username)
  @user != nil && password == "test"
end
return unless authenticated == true 
如果身份验证成功,

authenticate_or_request_with_http_basic将返回“true”。它在失败时返回401。

2 个答案:

答案 0 :(得分:1)

听起来像authenticate_or_request_with_http_basic是渲染或重定向。我猜你将它移动到before_filter时它会起作用,因为它返回false会取消回调链并导致第二次渲染不会发生?只是一个猜测...

答案 1 :(得分:1)

authenticate_or_request_with_http_basic调用render以发送执行HTTP基本身份验证所需的HTTP响应(状态码401 Unauthorized)。有关详细信息,请参阅Rails code