gpt4 book ai didi

ruby-on-rails-5 - 使用 protect_from_forgery 和 : :exception but redirect user to login page if session expired

转载 作者:行者123 更新时间:2023-12-05 07:35:44 24 4
gpt4 key购买 nike

我有一个带有登录功能的 Rails 应用程序protect_from_forgery with: :exceptionapplication_controller.rb 上设置。

我遇到了一些用户在执行以下操作时显示异常页面的问题:

  1. 使用浏览器打开两个选项卡进入登录屏幕。
  2. 使用第一个选项卡登录,然后退出。
  3. 切换到第二个选项卡,然后继续登录。
  4. 第二个选项卡导致出现异常屏幕,原因是 session cookie 已经更改,因为用户已使用另一个选项卡登录和注销。

我还考虑将 protect_from_forgery with: :exception 更改为 protect_from_forgery with: :reset_session 但它会允许本网站中提到的 CSRF 攻击:https://rubyplus.com/articles/4921-Rails-Forgery-Protection-Basics

我想知道其他 Rails 应用程序是如何解决这个问题的。

最佳答案

你可以在这里尝试一些事情:

1)拯救异常:

rescue_from ActionController::InvalidAuthenticityToken do
render text: 'Token expired/invalid' # Or render whatever you want :)
end

2) 覆盖 handle_unverified_request在你的应用程序 Controller 中:

def handle_unverified_request
flash[:alert] = 'You have already signed out or the session has expired. Please sign in again.'
# Store the current url so at after_sign_in_path_for it grabs this URL and not the new_user_session_path
store_location_for(:user, request.fullpath) # This is if you're using devise. It just store the last URL the user visited
redirect_to new_user_session_path # Redirect to the sign in path
end

3) 或者只是在您的 ApplicationController 中使用 prepend_before_action:

prepend_before_action :verify_user!, unless: :user_signed_in?

def verify_user!
flash[:alert] = 'You have already signed out or the session has expired. Please sign in again.'
# Store the current url so at after_sign_in_path_for it grabs this URL and not the new_user_session_path
store_location_for(:user, request.fullpath)# This is if you're using devise. It just store the last URL the user visited
redirect_to new_user_session_path # Redirect to the sign in path
end

希望对您有所帮助! :)

关于ruby-on-rails-5 - 使用 protect_from_forgery 和 : :exception but redirect user to login page if session expired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49356604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com