Rails 3 protected_from_forgery 无法正常工作?
我使用的是 Rails 3.0.2,默认情况下在 application_controller.rb 中有 protect_from_forgery
。
我想触发 InvalidAuthenticityToken
。
为此,我已将此 javascript 添加到我的页面中:
$('input[name=authenticity_token]').val('aaa')
使用 Firebug 检查 DOM 我看到 authenticity_token
隐藏字段已正确更新。
如果我提交表单并检查服务器的日志,我会看到相对参数已正确设置为“aaa”。我希望在处理请求时得到一个 InvalidAuthenticityToken
,因为它是正确的!
这怎么可能?
I am using Rails 3.0.2 which has protect_from_forgery
by default in application_controller.rb.
I wanted to trigger an InvalidAuthenticityToken
.
To do this I have added this javascript to my page:
$('input[name=authenticity_token]').val('aaa')
Checking the DOM with Firebug I see the authenticity_token
hidden field is correctly updated.
If I submit the form and check the log from the server I see the relative parameter is correctly set to 'aaa'. I would expect to get a InvalidAuthenticityToken
while the request is processed as it was correct!
How is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
真实性令牌/csrf 行为的文档已过时。在这些情况下,不再引发
InvalidAuthenticityToken
异常,而只是重置您的会话。如果您想以不同的方式(或旧的方式)处理此问题,您可以在控制器上的handle_unverified_request
中定义您自己的行为。The documentation for the authenticity token/csrf behavior is out of date. The
InvalidAuthenticityToken
exception is no longer thrown in these cases, instead your session is just reset. If you would like to handle this differently (or the old way) you can define your own behavior inhandle_unverified_request
on your controller.我还相信您必须重置表单所在 html 页面的元标记中的真实性令牌(我假设您在那里有 <%= csrf_meta_tag %> )。 Rails 检查表单中的令牌(您在上面的 javascript 中更改的令牌)或 html 页面的元标记中的令牌是否与 Rails 预期的真实性令牌匹配,如果其中任何一个匹配,则您的 InvalidAuthenticityToken 将获胜。不被触发....
I also believe you would have to reset the Authenticity token that resides in the meta tag of the html page that your form is in (I am assuming that you have the <%= csrf_meta_tag %> in there). Rails checks if either of the token in the form (that you changed in your javascript above) or the token in the meta tag of the html page match with Rails' expected authenticity token, and if ANY of them match, then your InvalidAuthenticityToken won't be triggered....