gpt4 book ai didi

ruby-on-rails - Rails CSRF 保护 + Angular.js : protect_from_forgery makes me to log out on POST

转载 作者:行者123 更新时间:2023-12-03 04:31:30 24 4
gpt4 key购买 nike

如果 application_controller 中提到了 protect_from_forgery 选项,那么我可以登录并执行任何 GET 请求,但在第一个 POST 请求时,Rails 会重置 session ,从而使我退出。

我暂时关闭了 protect_from_forgery 选项,但想将其与 Angular.js 一起使用。有什么办法可以做到这一点吗?

最佳答案

我认为从 DOM 读取 CSRF 值并不是一个好的解决方案,它只是一种解决方法。

这里是angularJS官网的文档http://docs.angularjs.org/api/ng.$http :

Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

To take advantage of this (CSRF Protection), your server needs to set a token in a JavaScript readable sessioncookie called XSRF-TOKEN on first HTTP GET request. On subsequentnon-GET requests the server can verify that the cookie matchesX-XSRF-TOKEN HTTP header

这是我根据这些说明的解决方案:

首先,设置cookie:

# app/controllers/application_controller.rb

# Turn on request forgery protection
protect_from_forgery

after_action :set_csrf_cookie

def set_csrf_cookie
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end

然后,我们应该在每个非 GET 请求上验证 token 。
由于 Rails 已经使用类似的方法构建了,我们可以简单地重写它来附加我们的逻辑:

# app/controllers/application_controller.rb

protected

# In Rails 4.2 and above
def verified_request?
super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
end

# In Rails 4.1 and below
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end

关于ruby-on-rails - Rails CSRF 保护 + Angular.js : protect_from_forgery makes me to log out on POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14734243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com