ruby-on-rails 仅Rails 7 API应用程序需要使用Devise进行会话存储

rqmkfv5c  于 2023-05-19  发布在  Ruby
关注(0)|答案(2)|浏览(123)

我有一个新的应用程序,我试图设置与devisedevise-jwt。由于某种原因,我的authenticate_user!调用导致错误,因为会话已被禁用:

{"status":500,"error":"Internal Server Error","exception":"ActionDispatch::Request::Session::DisabledSessionError: Your application has sessions disabled. To write to the session you must first configure a session store"

路线:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :clients, only: [:show]
      devise_for :users,
             controllers: {
                 sessions: 'users/sessions',
                 registrations: 'users/registrations'
             }
    end
  end
end

用户

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable,
         :jwt_authenticatable,
         jwt_revocation_strategy: JwtDenylist
end

控制器:

class API::V1::Users::SessionsController < Devise::SessionsController
  respond_to :json
  private
  def respond_with(resource, _opts = {})
    render json: { message: 'Logged.' }, status: :ok
  end
  def respond_to_on_destroy
    current_user ? log_out_success : log_out_failure
  end
  def log_out_success
    render json: { message: "Logged out." }, status: :ok
  end
  def log_out_failure
    render json: { message: "Logged out failure."}, status: :unauthorized
  end
end

class Api::V1::ClientsController < ApplicationController
    before_action :authenticate_api_v1_user!

    def show
    end
end

我还需要做什么?当我向http://localhost:3000/api/v1/clients/ID发出请求时,我希望得到的响应是:

=> <html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>%

而不是这个500错误。

ui7jx7zq

ui7jx7zq1#

我在GitHub上找到了一个解决方案:

config.session_store :cookie_store, key: '_interslice_session'
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use config.session_store, config.session_options

从这篇文章

b5lpy0ml

b5lpy0ml2#

在rails API_only上启用session时要小心。默认情况下,仅api应用程序禁用会话。
默认情况下,管理员需要存储会话。你可以简单地在devise.rb中添加false选项来存储。

config.warden do |manager|
   manager.scope_defaults :user, store: false
end

额外:对于那些想要访问sidekiq网站的人,这些人将只为sidekiq路由启用会话。

require 'sidekiq/web'

Sidekiq::Web.use ActionDispatch::Cookies
Sidekiq::Web.use ActionDispatch::Session::CookieStore, key: "_interslice_session"

Rails.application.routes.draw do
  # Sidekiq login auth bonus, of course u can improve the secutiry.
  Sidekiq::Web.use Rack::Auth::Basic do |username, password|
    username == 'username' && password == 'password'
  end

  mount Sidekiq::Web => "/sidekiq"
end

相关问题