新手问题 手机和谷歌浏览器提交表单显示 ActionController::InvalidAuthenticityToken

aoreki · 2017年05月21日 · 最后由 aoreki 回复于 2017年05月25日 · 2145 次阅读

环境:

1.ubuntu 上 rails server 开启服务,端口 3000

2.nginx 监听 8000 端口,nginx 配置如下

events {
    worker_connections  1024;
}
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    underscores_in_headers on;
    server {
         listen xx.xx.xx.xx:8000;
         root /home/ubuntu/blog/public;
         location / {
             proxy_pass http://xx.xx.xx.xx:3000/;
         }
         location ~ \.(css|js|jpg|png|gif) {
             root /home/ubuntu/blog/public;
         }
    }
}

现象:

1.Microsoft Edge 和 Firefox 访问 xx.xx.xx.xx:8000 提交表单正常

2.Microsoft Edge,Chrome,Firefox 访问 xx.xx.xx.xx:3000 提交表单正常

3.Chrome 访问 xx.xx.xx.xx:8000 提交表单显示 ActionController::InvalidAuthenticityToken

4.Chrome 版本 58.0.3029.110 (64-bit)

5.报错信息 (太长了,截选):

Processing by SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"UN2YDS8C5xIt7Wu2RDmOqC7fa5YgSeGOdNG/YTbZIXNH4MH7ZlFhsWmABC44uLO7YvN4cO72T8ecfu5U3v/i2Q==", "session"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

actionpack (5.0.2) lib/action_controller/metal/request_forgery_protection.rb:195:in `handle_unverified_request'
actionpack (5.0.2) lib/action_controller/metal/request_forgery_protection.rb:223:in `handle_unverified_request'
actionpack (5.0.2) lib/action_controller/metal/request_forgery_protection.rb:218:in `verify_authenticity_token'
activesupport (5.0.2) lib/active_support/callbacks.rb:382:in `block in make_lambda'
activesupport (5.0.2) lib/active_support/callbacks.rb:169:in `block (2 levels) in halting'
actionpack (5.0.2) lib/abstract_controller/callbacks.rb:12:in `block (2 levels) in <module:Callbacks>'
activesupport (5.0.2) lib/active_support/callbacks.rb:170:in `block in halting'
activesupport (5.0.2) lib/active_support/callbacks.rb:454:in `block in call'

问题: 这现象让人很疑惑,Rails App 应该没问题,nginx 感觉也没问题,只有 Chrome 的请求,经过 nginx,才会有问题,新人求教。

https://github.com/plataformatec/devise/issues/2734

Thank you guys! I've been struggling for days with authenticity token failure in chrome (in firefox it worked properly). After adding "proxy_set_header X-Forwarded-Proto $scheme;" to nginx config the problem is solved. I might messed up the config file when setting up ssl. Big thanks!!

pathbox 回复

那一页的方法我几乎都试了一遍,都没用,后来把 rails 默认的 puma 换成了 passenger,奇迹般的好了。神奇的问题,chrome 和 nginx 造成的问题,最后却因为换了 puma 解决了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号