为什么Rails会像这样放置csrf令牌(Why Rails puts csrf token like this)

编程入门 行业动态 更新时间:2024-10-07 20:29:57
为什么Rails会像这样放置csrf令牌(Why Rails puts csrf token like this)

我从来没有使用Rails(只能回答我的问题),但我看到它在每个页面中都有表单的CSRF令牌。 我不明白的是为什么它使用了两个meta标签:

<meta name="csrf-token" content="<%= form_authenticity_token %>" /> <meta name="csrf-param" content="authenticity_token" />

为什么不只是csrf-token元?

<meta name="csrf-token" content="<%= form_authenticity_token %>" />

csrf-param的用途是什么?

I've never used Rails (that only could answer my question), but I see it puts CSRF tokens in each page with forms. What I don't understand is why it uses two meta tags for that:

<meta name="csrf-token" content="<%= form_authenticity_token %>" /> <meta name="csrf-param" content="authenticity_token" />

Why not just the csrf-token meta?

<meta name="csrf-token" content="<%= form_authenticity_token %>" />

What's the use of csrf-param?

最满意答案

Rails允许您在与CSRF令牌相关的引擎盖下进行大量配置。 如果你喜欢,你可以改变参数的名称 - 但是如果你这样做, jQuery UJS驱动需要知道新参数的名称(因为它在Ajax请求中使用)。 这就是为什么这里有两个元参数:第一个是真正的真实性标记,但第二个是Rails的JavaScript驱动程序所要求的,以便知道第一个的名称。 (您可以在jQuery驱动程序或Prototype驱动程序中看到这一点。)

你可能会认为这会让你陷入某种疯狂的循环 - 为什么你不能用另一个元标记重命名csrf-param meta标签? 我认为这样做是为了让Rails轻松地采用现有的CSRF解决方案,而不需要大量的手动覆盖。 此外,它可以让你的应用程序稍微面向未来。 如果HTML5标准曾采用CSRF令牌的官方标签,并且Rails选择在未来版本中更改默认的CSRF标签,则JavaScript驱动程序根本不需要更改。

最终,我认为这与存在的真实原因最为接近:它可以防范CSRF系统中未来的变化,防止不必要的,甚至可能非常烦人的弃用。

Rails allows you to do a lot of configuration under the hood related to the CSRF token. If you like, you can change the name of the param -- but if you do, the jQuery UJS driver needs to know the name of the new parameter (since it's used in Ajax requests). That's why there are two meta params here: the first is the actual authenticity token, obviously, but the second is required by Rails' JavaScript drivers in order to even know the name of the first one. (You can see this in action in the jQuery driver or the Prototype driver.)

You could argue this gets you into some kind of crazy loop -- why can't you rename the csrf-param meta tag with another meta tag? I think this was done to allow Rails to easily adopt existing CSRF solutions without needing a lot of manual overrides. Also it allows your apps to be slightly future-proofed. If the HTML5 standard ever adopts an official tag for CSRF tokens, and Rails opts to change the default CSRF tag in a future version, the JavaScript drivers won't have to change at all.

Ultimately, I think that's closest to the real reason this exists: it's insurance against future changes in the CSRF system, preventing unnecessary and possibly extremely annoying deprecations down the road.

更多推荐

本文发布于:2023-07-27 08:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   会像   Rails   csrf   token

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!