[英]'protect_from_forgery' in Application controller in Rails
[英]Override the protect_from_forgery strategy in a controller
我想用两种不同的protect_from_forgery策略构建一个rails应用程序:一个用于Web应用程序,另一个用于API。
在我的应用程序控制器中,我有这行代码: protect_from_forgery with: :exception
以防止CSRF攻击,它工作得很好。
在我的API命名空间中,我创建了一个从我的应用程序控制器继承的api_controller,它是API命名空间中所有其他控制器的父类,我用以下代码修改了上面的代码: protect_from_forgery with: :null_session
。
遗憾的是,我在尝试发出POST请求时出错:“无法验证CSRF令牌真实性”。
我不想跳过API控制器中的verify_authenticity_token方法,我只想在我的应用程序中有两个不同的策略,那么如何覆盖应用程序控制器中定义的protect_from_forgery策略?
编辑 :好的,所以我最终做了我最初不想做的事情:改变我的api_controller的继承:它现在继承自ActionController :: Base,而不再是我的应用程序控制器。 它现在可以工作但是:
因此,如果有人有真正的方法来覆盖这种方法,我会很感激。
如果您在应用程序控制器中将protect_from_forgery with: :exception
保留为protect_from_forgery with: :exception
,但是您将以下内容放在API控制器中,该怎么办?
skip_before_action :protect_from_forgery
protect_from_forgery with: :null_session
这样,您仍然可以为Web应用程序中的所有控制器获得标准的CSRF攻击保护,但您也会获得API方法的空会话行为。
我正在运行具有类似结构的应用程序 - Web App + API。 我解决了这样的CSRF问题:
码:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception, if: :isWebRequest?
def isWebRequest?
request.subdomains[-1] != 'api'
end
end
晚会,但这样的事情可以做到:
class YourCustomStrategy
def initialize(controller)
end
def handle_request
end
end
在您的ApplicationController中或您想要的位置:
class ApplicationController < ActionController::Base
protect_from_forgery with: YourCustomStrategy
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.