ruby-on-rails “authenticate_user”返回最后创建的用户,而不是使用Devise和JWT在仅限Rails API的应用程序中进行身份验证

kknvjkwl  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(138)

我正在使用Rails与Devise和Devise JWT构建一个仅API的应用程序进行身份验证,我已经将JWT撤销策略设置为self,并为Devise会话和注册创建了控制器,当我注册用户时,我能够获得授权令牌,但当我尝试访问其他受保护的路由时我没有正确的认证,可以访问没有令牌的路由。我如何确保所有受保护的路由都正确地执行了认证

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  include Devise::JWT::RevocationStrategies::JTIMatcher

  devise :database_authenticatable, :registerable, :validatable,
         :jwt_authenticatable, jwt_revocation_strategy: self

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

    def jwt_payload
        super.merge('foo' => 'bar')
      end
    validates :email, presence: true,format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
    validates :password, presence: true, length: {minimum: 10}

end

配准控制器

class Users::RegistrationsController < Devise::RegistrationsController

  respond_to :json
  private

  def respond_with(resource, _opts = {})

    if resource.persisted?
      render json: {
        status: {code: 200, message: 'Signed up sucessfully.'},
        data: UserSerializer.new(resource).serializable_hash[:data][:attributes]
      }
    else
      render json: {
        status: {message: "User couldn't be created successfully. #{resource.errors.full_messages.to_sentence}"}
      }, status: :unprocessable_entity
    end
  end
end

用户控制器

class UsersController < ApplicationController
  before_action :authenticate_user!
  skip_before_action :verify_authenticity_token, only: [:create]

   def show
     @user = User.find(params[:id])
     render :json => @user
   end

   def create
    @user = User.new(user_params)
      @user.password_confirmation = params[:confirm_password]
      @user.password = params[:password]
    if @user.save
      render json: @user, status: :created  
    else
      render json: @user.errors, status: :unprocessable_entity
    end

   end 

    def user_params
      
      params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end
    

end

我已经在上面的控制器中添加了一个before action钩子,但是如果可以进行API调用来显示action方法,我就可以获取带有授权令牌的响应,
我不确定,我错过了什么?

2ledvvac

2ledvvac1#

可能是您的SessionStore有问题:
如果您正在使用启用了会话存储和默认Devise设置的Rails应用程序,那么无论头部中是否存在令牌,都有可能从会话中验证相同来源的请求。
https://github.com/waiting-for-dev/devise-jwt#session-storage-caveat
如果您仅使用API,则可以使用以下命令禁用:

# config/initializers/session_store.rb
Rails.application.config.session_store :disabled

相关问题