首页 > 解决方案 > Ruby on Rails - 无法在某些操作中设置 cookie

问题描述

我正在尝试设置target_path非授权用户尝试访问的 cookie,并在授权后将他重定向到目标。一切正常,但后来我尝试使用 POST/PATCH/PUT 请求设置为目标edit_test_pathcreate_test_path其他方法,似乎没有设置任何 cookie。可能是什么情况?

application.rb - 我在这里设置 cookie。authenticate_user!调用几乎每个before_action控制器

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session

  helper_method :current_user,
                :logged_in?

  private

  def authenticate_user!
    unless current_user
      cookies[:target_path] = request.path_info

      redirect_to login_path, alert: 'Verify Email or Password'
    end
  end

  def current_user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
  end

  def logged_in?
    current_user.present?
  end
end

session_controller.rb - 我正在尝试从此处的 cookie 重定向到目标

class SessionsController < ApplicationController
  def new; end

  def create
    user = User.find_by(email: params[:email])

    if user&.authenticate(params[:password])
      session[:user_id] = user.id

      cookies[:target_path] ? (redirect_to cookies[:target_path]) : (redirect_to root_path) # With verb POST cookies don't work
    else
      flash.now[:alert] = 'Verify Email or Password'
      render :new
    end
  end

  def exit
    session[:user_id] = nil

    redirect_to login_path
  end
end

标签: ruby-on-railscookiesauthorization

解决方案


我不认为,你可以用 POST/PUT/PATCH 请求来做到这一点。当您这样做redirect_to时,rails会在您的情况下发送带有参数中指定的302 Found响应或。locationredirect_tocookies[:target_path]root_path

然后浏览器理解它应该进行重定向并将 GET 请求发送到location 标头中指定的 URL。您不能也不应该尝试告诉它执行 POST/PUT/PATCH 请求 - 这些类型的请求通常还需要与请求一起出现的某种数据(例如提交的表单)。无论如何,您在重定向到登录页面期间丢失了所有这些数据。

我想说的是 - 仅将这些重定向用于 GET 请求。它不适用于 POST/PUT/PATCH。


推荐阅读