Configuring Cookie Sharing and Session Management Across Subdomains in Rails with Devise-Masquerade

I am using devise-masquerade gem with rails 7.0.4. my site admin is log in on URL “HTTP://test.localhost:3000/admin/login” and using “login as” feature provide by devise-masquerade gem, everything works fine when admin login to “HTTP://test.localhost:3000” but when admin login on to “HTTP://xyz.localhost” getting as unauthorized request error. I have tried by following way: 1.session_store.rb

module SessionConfig
    def self.cookie_settings(domain = nil)
        domain ||= '.localhost'
      {
        key:"my_app_key",
        domain: domain,
        path: '/',
        same_site: :lax,  
        httponly: true,  # Cookie is not accessible via JavaScript
        tld_length: 2,
        secure: false,  # Change to `true` if you are using HTTPS
      }
    end
end
   
Rails.application.config.session_store :cookie_store, **SessionConfig.cookie_settings

Also, I configured it in application.rb

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore

Please I would like to update cookies as:

class MasqueradesController < ApplicationController
  def show
    # Retrieve the masqueraded resource based on the provided parameter
    resource = resource_class.find(params[:format])
    
    # Sign in as the masqueraded resource
    masquerade_sign_in(resource)
    

    
    # Mark the session as masqueraded
    session[:masquerade] = true
    
    
    if subdomain != current_subdomain(xyz != test)
      # Update session and redirect to the new subdomain
      update_session(subdomain)
    else
      # Redirect to the root URL of the current subdomain
      redirect_to root_url
    end
  end

  private

  def update_session(subdomain)
    # Generate the root URL for the specified subdomain
    url = root_url(subdomain: subdomain, host: "localhost")
    
    # Parse the domain from the URL
    domain = URI.parse(url).host
    
    # Retrieve the session ID
    session_id = session[:session_id]
    
    # Configure the cookie settings
    cookie_options = {
      key: my_app_session,
      value: session_id,
      domain: domain,
      expires: 3.days.from_now
    }
    
    # Set the cookie for the new domain
    cookies[cookie_options[:key]] = cookie_options
    
    # Redirect to the root URL of the new subdomain
    redirect_to root_url(subdomain: subdomain, host: 'localhost'), allow_other_host: true
  end
end