首页 > 解决方案 > 在 Rails 中将 devise-jwt 添加到现有用户模型时的问题

问题描述

我试图将 devise-jwt 添加到我拥有的现有应用程序中。我现在添加 API 端点,并且想使用我已经拥有的相同模型

我在本文之后添加了 gem devise-jwt:https ://medium.com/@mazik.wyry/rails-5-api-jwt-setup-in-minutes-using-devise-71670fd4ed03

我已经配置了我的 devise.rb 文件:

config.jwt do |jwt|
  jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
  jwt.dispatch_requests = [
    ['POST', %r{^/login$}]
  ]
  jwt.revocation_requests = [
    ['DELETE', %r{^/logout$}]
  ]
  jwt.expiration_time = 1.day.to_i
end

为它创建了我的 jwt_blacklist.rb 和迁移:

class CreateJwtBlacklist < ActiveRecord::Migration[6.0]
  def change
    create_table :jwt_blacklist do |t|
      t.string :jti, null: false
    end
    add_index :jwt_blacklist, :jti
  end
end

class JWTBlacklist < ApplicationRecord
  include Devise::JWT::RevocationStrategies::Blacklist

  self.table_name = 'jwt_blacklist'
end

当我尝试将这些行添加到我的 user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
        :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook],
        :jwt_authenticatable,
        jwt_revocation_strategy: JWTBlacklist

当我尝试启动我的服务器时,我得到:

/Users/fmaymone/.rvm/gems/ruby-2.6.3/gems/activesupport- 
6.0.0/lib/active_support/dependencies.rb:511:in `load': /booksculp/app/models/user.rb:6: 
syntax error, unexpected ',', expecting => (SyntaxError)
    :jwt_authenticatable ,

有人知道我在这里做错了什么吗?

谢谢

标签: ruby-on-railsrubydevise

解决方案


将您的User模型更改为以下内容:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
        :recoverable, :rememberable, :trackable, :validatable, :omniauthable,
        :jwt_authenticatable, jwt_revocation_strategy: JWTBlacklist, omniauth_providers: [:facebook]

推荐阅读