Rails的CSRF保护+ Angular.js:protect_from_forgery让我退出的POST [英] Rails CSRF Protection + Angular.js: protect_from_forgery makes me to log out on POST

查看:189
本文介绍了Rails的CSRF保护+ Angular.js:protect_from_forgery让我退出的POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在 protect_from_forgery 选项在application_controller提到的,然后我就可以登录并执行任何GET请求,但在第一个POST请求的Rails复位会话,它记录了我出去。

If the protect_from_forgery option is mentioned in application_controller, then I can log in and perform any GET requests, but on very first POST request Rails resets the session, which logs me out.

我把 protect_from_forgery 选项暂时关闭,但想用Angular.js使用它。是否有某种方式来做到这一点?

I turned the protect_from_forgery option off temporarily, but would like to use it with Angular.js. Is there some way to do that?

推荐答案

我觉得从DOM读取CSRF值不是一个很好的解决方案,它只是一个解决方法。

I think reading CSRF-value from DOM is not a good solution, it's just a workaround.

下面是一个文档形式angularJS官方网站http://docs.angularjs.org/api/ng.$http

Here is a document form angularJS official website http://docs.angularjs.org/api/ng.$http :

由于只在您的域中运行的JavaScript可以读取cookie,您的服务器可以放心,XHR从JavaScript来在域上运行。

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.

要充分利用这个(CSRF保护),你的服务器需要设置令牌在JavaScript可读会议
  饼干叫XSRF-TOKEN第一次HTTP GET请求。在随后的
  非GET请求服务器可以验证cookie的比赛
  的X XSRF-TOKEN HTTP头

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

下面是我的解决方案,根据这些指示:

Here is my solution based on those instructions:

首先,设置Cookie:

First, set the cookie:

# app/controllers/application_controller.rb

# Turn on request forgery protection
protect_from_forgery

after_filter :set_csrf_cookie_for_ng

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

那么,我们应验证令牌上的每个非GET请求。结果
由于Rails的已用类似的方法建立,我们可以只是简单地覆盖它来追加我们的逻辑:

Then, we should verify the token on every non-GET request.
Since Rails has already built with the similar method, we can just simply override it to append our logic:

# 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

这篇关于Rails的CSRF保护+ Angular.js:protect_from_forgery让我退出的POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆