如果在application_controller中提到了protect_from_forgery
选项,那么我可以登录并执行任何GET请求,但是在第一个POST请求上,Rails重置了 session ,这使我注销。
我暂时关闭了protect_from_forgery
选项,但想与Angular.js一起使用。有什么办法吗?
最佳答案
我认为从DOM读取CSRF值不是一个好的解决方案,这只是一种解决方法。
这是angularJS官方网站http://docs.angularjs.org/api/ng.$http的文件格式:
这是基于这些说明的我的解决方案:
首先,设置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 Protection + Angular.js:protect_from_forgery让我注销POST,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14734243/