【问题标题】:Strange ruby blocks behavior when implementing Rails token auth实现 Rails 令牌身份验证时奇怪的 ruby​​ 阻止行为
【发布时间】:2014-01-12 07:50:26
【问题描述】:

在尝试在 Rails 中实现令牌身份验证的过程中,我遇到了这种行为:

class AppController < ActionController::Base
    before_filter :restrict_access

    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
        false
      end
    end

这将按预期拒绝所有请求。

但是,如果我将“false”更改为“return false”,它接受所有请求。

def restrict_access
  authenticate_or_request_with_http_token do |token, options|
    return false
  end
end 

这怎么可能?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    为了拒绝请求,before_filter 必须调用重定向或渲染。

    现在这个方法是这样的:

    # File actionpack/lib/action_controller/metal/http_authentication.rb, line 389
    def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
      authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
    end
    

    return false 在这里所做的,是在 request_http_token_authentication 能够运行之前从方法(不仅仅是块)中过早地中断,这就是实际呈现 403 页面的方法,如下所示:http://apidock.com/rails/ActionController/HttpAuthentication/Token/authentication_request

    所以你最终会得到这样的东西:

    return(false) || request_http_token_authentication(realm)
    

    而不是这个:

    false || request_http_token_authentication(realm)
    

    这就是为什么你不应该在块中使用return 语句。

    在此处查看更多信息:Using 'return' in a Ruby block

    【讨论】:

    • “这就是为什么你不应该在块中使用 return 语句”- 没错- 我是个白痴。很好的答案,谢谢。
    • return 块中的语句很好,只是您需要了解如何使用它们!这里有更多细节Returning from a Ruby proc: beware of where you land
    猜你喜欢
    • 2018-05-15
    • 2015-10-24
    • 2010-12-17
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2013-09-22
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多