首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >protect_from_forgery -秩序重要吗?

protect_from_forgery -秩序重要吗?
EN

Stack Overflow用户
提问于 2017-08-02 00:08:47
回答 1查看 378关注 0票数 2

我读过这篇文章https://nvisium.com/blog/2014/09/10/understanding-protectfromforgery/,如果我正确理解,在Rails 3中默认情况下,如果我们有一个控制器,如下所示:

代码语言:javascript
复制
class ApplicationController < ActionController:Base
  protect_from_forgery
end

最终会发生的是(在攻击者的情况下)会话将被销毁。这意味着,如果我们正在检查用户是否经过身份验证,因为没有会话,它将停止请求。

所以,我的问题是,我相信:

代码语言:javascript
复制
class ApplicationController < ActionController:Base
  protect_from_forgery
  before_action :authenticate_user

  private

  def authenticate_user
    raise NotAuthenticated unless session.key?(:user)
  end
end

是正确的做法,而不是

代码语言:javascript
复制
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应该是我们在控制器中做的第一件事。

我的假设是正确的,还是我遗漏了操作顺序在控制器中的工作方式?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-02 00:14:14

这两种方法的顺序并不重要,不重要。

原因与这些方法何时被执行有关:这些方法是类级方法,在Ruby加载文件时在类本身的上下文中执行。

查看protect_from_forgery的源代码

代码语言:javascript
复制
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

这些宏基本上是在调用类时向类添加代码的宏,这种宏是元编程的一种形式。您可以将类中的方法调用替换为手动设置这些内容,这将是相同的。

当您的代码第一次加载时,在应用程序启动之前,这一切都会发生。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45449467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档