【问题标题】:Rails devise-jwt session storageRails 设计-jwt 会话存储
【发布时间】:2020-08-21 20:33:13
【问题描述】:

devise-jwt gem 文档说,如果启用了会话存储,您必须跳过它以进行 jwt 身份验证。它说你应该在 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]

routes.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?

【问题讨论】:

  • 嗨 @Samuel,我猜你正在使用以下 gem github.com/waiting-for-dev/devise-jwt。几天前我也用过同样的东西。您不必从模型中删除 :database_authenticatable。只需更改配置文件config.skip_session_storage 在项目中我必须同时保留会话和 jwt。在这种情况下,我必须在 session_store.rb 配置文件和 application_controller 中添加Rails.application.config.session_store :cookie_store json 请求必须添加'protect_from_forgery with: :null_session if request.format.json?
  • 我使用了另一种解决方案,我发布了.. 稍后我会试试你的。
  • 我遇到了同样的问题。我的解决方案在 devise-jwt 文档中。我在我的非 API 用户模型上使用了 self.skip_session_storage = [:http_auth, :params_auth],所以我没有完全跳过它。

标签: ruby-on-rails devise jwt jwt-auth devise-jwt


【解决方案1】:

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

monkeypatch:config/initializers/warden/proxy.rb

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

而且您必须为 api 身份验证和默认行为设置单独的路由:

routes.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2011-12-12
    相关资源
    最近更新 更多