You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails集成Devise注册时出现InvalidAuthenticityToken错误求助

解决ActionController::InvalidAuthenticityToken错误的方案

1. 移除表单中多余的CSRF相关代码

你的所有Devise表单里重复添加了<%= csrf_meta_tags %>和<%= form_authenticity_token %>,这会导致验证冲突:

  • csrf_meta_tags仅需在application.html.erb的head标签中保留一份,无需在每个表单内重复添加
  • simple_form_for会自动生成正确的CSRF隐藏字段,手动添加form_authenticity_token会产生重复token,导致验证失败

以注册表单为例,修改后代码如下:

<h2>Sign up</h2>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>
  <div class="form-inputs">
    <%= f.input :email,
                required: true,
                autofocus: true,
                input_html: { autocomplete: "email" }%>
    <%= f.input :password,
                required: true,
                hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
                input_html: { autocomplete: "new-password" } %>
    <%= f.input :password_confirmation,
                required: true,
                input_html: { autocomplete: "new-password" } %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

所有其他Devise表单都需要做同样修改,移除表单内的csrf_meta_tags和form_authenticity_token。

2. 适配Rails Turbo(针对Rails 7+)

Rails 7默认启用Turbo,Devise表单需处理Turbo兼容性,两种方案可选:

方案A:给表单添加Turbo禁用属性

在每个simple_form_for的html选项中添加data: { turbo: false },示例:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { data: { turbo: false } }) do |f| %>
  <!-- 表单内容 -->
<% end %>

方案B:安装Devise Turbo兼容补丁

在Gemfile中添加兼容gem:

gem "devise-turbo"

执行以下命令完成安装:

bundle install
rails generate devise_turbo:install

该gem会自动处理Devise与Turbo的兼容性问题。

3. 检查Session与Host配置

在development.rb中,确保session cookie的domain配置与访问域名一致:

# 在development.rb中添加或修改
config.session_store :cookie_store, key: '_railsruby3_session', domain: :all, tld_length: 2

如果是本地测试,可将邮件配置的host改为localhost:

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

4. 清除浏览器缓存与Cookie

浏览器缓存的旧CSRF Token可能导致验证失败,完全清除浏览器缓存和Cookie后重新测试。

5. 验证CSRF Token传递

通过浏览器开发者工具的Network标签,查看注册请求的Form Data,确认是否存在authenticity_token字段,且其值与页面head中csrf-token meta标签的值一致。


内容的提问来源于stack exchange,提问作者Aly Dabbous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:00:18