单页应用程序和CSRF令牌 [英] Single Page Application and CSRF Token

查看:364
本文介绍了单页应用程序和CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用单页应用程序(React,Ember,Angular,我不关心)和Rails CSRF保护机制。

I need to use a Single Page Application (React, Ember, Angular, I don't care) with Rails CSRF protection mechanism.

我想知道是否我需要在 ApplicationController 中创建一个令牌evey时间,如下所示:

I'm wondering if I need to create a token evey time in the ApplicationController like this:

class ApplicationController < ActionController::Base

  after_action :set_csrf_cookie

  def set_csrf_cookie
    cookies["X-CSRF-Token"] = form_authenticity_token
  end

end

或者我可以创建一次令牌

每次会话或每次(非GET)请求?

Per session or per (non-GET) request?

我认为令牌仍然有效,直到会话有效,对吗?

I think the token is still valid until the session is valid, right?

CLARIFY

我看到Rails默认应用(服务器呈现的页面)每次导航页面时都会更新csrf-token。所以每次都改变。

I see Rails default application (server-rendered pages) update csrf-token each time I navigate a page. So every time it changes.

所以在我的情况下,如果我为每个 after_action 创建一个新令牌,那么以前的CSRF -Token仍然适合该会话。那么,如何使前一个令牌无效?我必须吗?

So in my situation if I create a new token for each after_action the previous CSRF-Token is still good for that session. So, how to invalidate the previous token? I have to?

因为只有我无效才有意义,对吗?

Because only if I invalidate it makes sense, right?

推荐答案

客户端(SPA)



您只需要每次会话获取CSRF令牌一次。您可以在浏览器中保留它并在每个(非GET)请求上发送它。

Client side (SPA)

You only need to grab the CSRF token once per session. You can hold onto it in the browser and send it on every (non-GET) request.

Rails似乎会在每个请求上生成一个新的CSRF令牌,但它将接受来自该会话的任何生成的令牌。实际上,它只是为每个请求使用一次性填充屏蔽单个令牌,以防止SSL BREACH攻击。有关详细信息,请访问 https://stackoverflow.com/a/49783739/2016618 。您不需要跟踪/存储这些令牌。

Rails will appear to generate a new CSRF token on every request, but it will accept any generated token from that session. In reality, it is just masking a single token using a one-time pad per request, in order to protect against SSL BREACH attack. More details at https://stackoverflow.com/a/49783739/2016618. You don't need to track/store these tokens.

我强烈建议使用Rails的 protect_from_forgery 指令而不是自己在头文件中编码CSRF令牌。它会为每个请求生成一个不同的屏蔽标记。

I strongly suggest using Rails's protect_from_forgery directive rather than encoding the CSRF token in a header yourself. It will generate a different masked token per request.

你自然可以用很多代码重现这个,但我不明白为什么你需要。

You can certainly reproduce this yourself with not that much code, but I don't see why you'd need to.

是!如果您正在使用cookie进行身份验证,您需要CSRF保护。这是因为cookie随每个请求一起发送,因此恶意网站可以向您的站点发送POST请求并代表登录用户执行请求。 CSRF令牌可以防止这种情况,因为恶意站点不会知道CSRF令牌。

Yes! If you are authenticating with a cookie, you need CSRF protection. This is because cookies are sent with every request, so a malicious website could send a POST request to your site and perform requests on behalf of a logged in user. The CSRF token prevents this, because the malicious site won't know the CSRF token.

这篇关于单页应用程序和CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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