[英]Intermittent Rails 5 ActionController::InvalidAuthenticityToken
Context: a Rails app in production, hosted on Heroku, that has around 800 users. 上下文:一个在Heroku上托管的量产的Rails应用,拥有大约800个用户。
For some reason, I have seen a few users experience an error: 由于某种原因,我看到一些用户遇到错误:
ActionController::InvalidAuthenticityToken
[GEM_ROOT]/gems/actionpack-5.1.4/lib/action_controller/metal/request_forgery_protection.rb:195
For requests to POST /students/:id/registrations
. 对于POST /students/:id/registrations
请求。
It is intermittent, and very few users experience the error. 它是间歇性的,很少有用户遇到此错误。
Clients are Safari 11.0 on iPads. 客户端是iPad上的Safari 11.0。
ApplicationController: ApplicationController中:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!, unless: :devise_controller?
before_action :restrict_from_students, unless: :devise_controller?
# ...
end
RegistrationsController: RegistrationsController:
class RegistrationsController < ApplicationController
skip_before_action :restrict_from_students, only: :create
# ...
end
Is there some scenario (re-POSTing the request, auth timeout but submitting, lack of JS) that would cause this? 是否存在某种情况(重新发布请求,验证超时但提交,缺少JS)会导致这种情况? I cannot seem to reproduce it. 我似乎无法复制它。
Thanks to the rubber duck, I have reproduced the issue. 感谢橡皮鸭,我转载了这个问题。
The solution here is to use rescue_from
to likely redirect the user to the sign in page. 此处的解决方案是使用rescue_from
可能将用户重定向到登录页面。
Thank you rubber duckie! 谢谢橡皮鸭!
I was having a similar issue. 我有一个类似的问题。
Use rescue_from
in the application controller and redirect somewhere useful with a notification. 在应用程序控制器中使用rescue_from
,并在有用通知的地方重定向。 In my case I attempt to redirect the user back to where they were to reattempt their action, or to the home page as a fallback. 在我的情况下,我尝试将用户重定向到他们要重新尝试其操作的位置,或者将其重定向到主页。
Example for rails 5: 导轨5的示例:
class ApplicationController < ActionController::Base
rescue_from ActionController::InvalidAuthenticityToken,
with: :handle_invalid_token
def handle_invalid_token
redirect_back fallback_location: root_path,
notice: 'Stale session detected'
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.