当我尝试使用 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 的方式吗?