方法“verify_expiration”的 jwt 错误

jwt error with method `verify_expiration'

当我尝试使用 JWT 解码从前端发回的令牌时,我遇到了一个问题。当令牌被解码为“2”时,这是我在后端抓取用户的用户 ID,我得到了这个错误:“NoMethodError: undefined method `include?' for 2:Integer”,这是来自 JWT 源代码中的以下代码:

def verify_expiration
return unless @payload.include?('exp')
raise(JWT::ExpiredSignature, 'Signature has expired') if @payload['exp'].to_i <= (Time.now.to_i - exp_leeway)
end

我应该怎么做才能解决这个问题?

我的应用程序控制器文件如下所示:

class ApplicationController < ActionController::API

    def encode_token(payload)
        JWT.encode(payload, 'secret')
    end

    def auth_header_token
        request.headers['Authorization'].split(' ')[1]
    end

    def session_user
      binding.pry
      decoded_hash = decoded_token
      if !decoded_hash.empty?
        user_id = decoded_hash[0]["user_id"]
        user = User.find_by :id=>user_id
      end
    end


    def decoded_token
        if auth_header_token
          begin
            JWT.decode(auth_header_token, 'secret',true, algorithm: 'HS256')
          rescue JWT::DecodeError
            []
          end
        end
    end
end

我的 session_controller 看起来像这样:

class SessionController < ApplicationController
    def login
        user = User.find_by :email=>params[:email]
        if user && user.authenticate(params[:password])
            payload = user.id
            token = encode_token(payload)
            render json: {
                user:user, include: ['order', 'favorites','orders.dishes','favorites.dishes'], 
                jwt:token
            }
        else
            render json: {status: "error", message: "We don't find such an user according to your information,please try again."}
        end
    end


    def auto_login
        if session_user
            render json: session_user
        else
            render json: {errors: "No User Logged In."}
        end     
    end
end

我是否应该更改编码方式 user_id?

刚刚发现问题是我需要将 user_id 编码为对象,而不仅仅是 id 本身,因为 JWT 可以将其作为对象进行检查,这就是错误消息的来源。所以,而不是

payload = user.id
token = encode_token(payload)

应该设置:

payload = {user_id: user.id}
token = encode_token(payload)