0

devise-jwt gem 文档说,如果启用了会话存储,则必须跳过它以进行 jwt auth。它说你应该在 devise.rb 上设置:

config.skip_session_storage = [:http_auth, :params_auth]

你应该禁用 :database_authenticable。这部分我完全不明白。如果在我的用户模型中,我删除:database_authenticable,我为登录配置的路由变得不可用:

ActionController::RoutingError (没有路由匹配 [POST] "/login"):

用户.rb

class User < ApplicationRecord
  rolify role_join_table_name: 'public.user_roles'
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable

  # devise :database_authenticatable,
  devise :registerable,
         :recoverable,
         :rememberable,
         :validatable,
         :jwt_authenticatable,
         jwt_revocation_strategy: Devise::JWT::RevocationStrategies::Null
end

设计.rb

config.skip_session_storage = %i[http_auth params_auth]

路线.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html

  devise_for :users, defaults: { format: :json },
                     path: '',
                     path_names: {
                       sign_in: 'login',
                       sign_out: 'logout',
                       registration: 'signup'
                     },
                     controllers: {
                       sessions: 'users/sessions',
                       registrations: 'users/registrations'
                     }
end

我应该怎么做才能保持会话,而不是 jwt auth?

4

1 回答 1

1

好吧,在调整了我在这篇文章https://blog.siliconjungles.io/devise-jwt-with-sessions-hybrid中找到的解决方案后,答案如下:

猴子补丁:config/initializers/warden/proxy.rb

module Warden
  class Proxy
    def user(_argument = {})
      if request.format.json?
        return nil
      end
    end
  end
end

并且您必须为 api 身份验证和默认行为分开路由:

路线.rb

namespace :api do
    namespace :v1 do
      devise_scope :user do
        post 'auth/signup', to: 'registrations#create'
        post 'auth/signin', to: 'sessions#create'
        delete 'auth/signout', to: 'sessions#destroy'
      end
    end
  end

  devise_for :users
于 2020-08-25T20:03:54.563 回答