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

生产环境中Devise的authenticity_token验证失败问题求助

生产环境启用config.force_ssl=true时Devise注册/登录触发CSRF令牌验证错误

错误日志

尝试注册时,日志输出如下:

INFO -- : [] Started POST "/users" for x.x.x.x at 2024-10-25 17:13:59 +0000
INFO -- : [] Processing by Devise::RegistrationsController#create as TURBO_STREAM
INFO -- : []   Parameters: {"authenticity_token"=>"xbBO-i0Q8RfwaMauQWKQmS5ynMMZ1YDC0WeOZQvParHwqXzOWSKWljOsiSZpNvMX57LZovgNdXU0OP0qpUVorg", "user"=>{"email"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
WARN -- : [] Can't verify CSRF token authenticity.
INFO -- : [] Completed 422 Unprocessable Content in 2ms (ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 0.0ms)
ERROR -- : [] ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity.):

CSRF令牌不匹配情况

检查发现页面meta标签中的CSRF令牌与请求中的authenticity_token不一致:

注册页面源码中的令牌

<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="K5MkNhqyz5xvGNhIAlRe31thoUaxLQsyqurk3F7ZS1NCr-2mVzUkrbgeWpyxzA9x3NGhxA70UsVXQrRAntmpIw" />

请求中携带的令牌

"authenticity_token"=>"xbBO-i0Q8RfwaMauQWKQmS5ynMMZ1YDC0WeOZQvParHwqXzOWSKWljOsiSZpNvMX57LZovgNdXU0OP0qpUVorg"

Apache SSL站点配置

当前使用的Apache虚拟主机配置如下:

<VirtualHost *:443>
  ServerName domain.org
  ServerAlias www.domain.org
  DocumentRoot /path/public
  RailsEnv production
  PassengerRuby /path/.rbenv/shims/ruby

  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/path/public">
      Options FollowSymLinks
      Require all granted
  </Directory>

  SSLEngine On
  SSLCertificateFile      /path/fullchain.pem
  SSLCertificateKeyFile   /path/privkey.pem

  #For RoR "Mongrel"
  RequestHeader set X-Forwarded-Proto "https"

  #Hack for IE
  SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
</VirtualHost>

问题定位

  • 开发环境下注册/登录功能正常,无CSRF验证错误
  • 将Rails配置config.force_ssl=false后,生产环境功能恢复正常
  • 确定问题仅在启用config.force_ssl=true时触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:02:41