我读过这篇文章https://nvisium.com/blog/2014/09/10/understanding-protectfromforgery/,如果我正确理解,在Rails 3中默认情况下,如果我们有一个控制器,如下所示:
class ApplicationController < ActionController:Base
protect_from_forgery
end最终会发生的是(在攻击者的情况下)会话将被销毁。这意味着,如果我们正在检查用户是否经过身份验证,因为没有会话,它将停止请求。
所以,我的问题是,我相信:
class ApplicationController < ActionController:Base
protect_from_forgery
before_action :authenticate_user
private
def authenticate_user
raise NotAuthenticated unless session.key?(:user)
end
end是正确的做法,而不是
class ApplicationController < ActionController:Base
before_action :authenticate_user
protect_from_forgery
private
def authenticate_user
raise NotAuthenticated unless session.key?(:user)
end
end换句话说,protect_from_forgery应该是我们在控制器中做的第一件事。
我的假设是正确的,还是我遗漏了操作顺序在控制器中的工作方式?
发布于 2017-08-02 00:14:14
这两种方法的顺序并不重要,不重要。
原因与这些方法何时被执行有关:这些方法是类级方法,在Ruby加载文件时在类本身的上下文中执行。
查看protect_from_forgery的源代码
def protect_from_forgery(options = {})
options = options.reverse_merge(prepend: false)
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
self.request_forgery_protection_token ||= :authenticity_token
before_action :verify_authenticity_token, options
append_after_action :verify_same_origin_request
end这些宏基本上是在调用类时向类添加代码的宏,这种宏是元编程的一种形式。您可以将类中的方法调用替换为手动设置这些内容,这将是相同的。
当您的代码第一次加载时,在应用程序启动之前,这一切都会发生。
https://stackoverflow.com/questions/45449467
复制相似问题