解决 Can't Verify CSRF Token Authenticity 错误

问题现象

今天偶尔看看一个项目的代码,然后想运行看看,通过localhost:3000访问,登陆的时候一直报下面的错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Started POST "/users/sign_in" for 127.0.0.1 at 2014-11-13 23:11:54 +0800
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"4HS675PeZDP+xBZkb45AJxQouoywke3lAJOvA3IFLt8=", "user"=>{"login"=>"xxx@test.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "
commit"=>"login"}

Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 100ms

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
  actionpack (4.1.1) lib/action_controller/metal/request_forgery_protection.rb:176:in `handle_unverified_request'
  actionpack (4.1.1) lib/action_controller/metal/request_forgery_protection.rb:202:in `handle_unverified_request'
  devise (3.2.4) lib/devise/controllers/helpers.rb:182:in `handle_unverified_request'
  actionpack (4.1.1) lib/action_controller/metal/request_forgery_protection.rb:197:in `verify_authenticity_token'
  activesupport (4.1.1) lib/active_support/callbacks.rb:424:in `block in make_lambda'
  activesupport (4.1.1) lib/active_support/callbacks.rb:160:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:160:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `call'
  activesupport (4.1.1) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.1) lib/action_controller/metal/rescue.rb:29:in `process_action'

原因推测

google 搜了下,很多人是ajax提交登陆的时候,没有设置authenticity_token才会发生, 但我这个是有authenticity_token的。

解决方法

最后发现原来此项目的session_store.rb配置了特定的域名,应该是为了子域名session共享而配置的。

1
2
3
4
Lvh::Application.config.session_store :cookie_store, key: '_lvh_session', domain: {
  production: '.lvh.com',
  development: '.lvh.local'
}.fetch(Rails.env.to_sym, :all)

所以本地开发环境访问的时候必须使用 lvh.local:3000访问, 这样登陆就没有问题了。

评论