首页 > 解决方案 > 如何修复错误 TypeError(没有将 nil 隐式转换为字符串):lib/json_web_token.rb:5:in `encode'?

问题描述

我有一个简单的 Jwt 身份验证在本地环境中完美运行,但是当上传到 heroku 时会出现以下错误!

TypeError(没有将 nil 隐式转换为字符串):lib/json_web_token.rb:5:in `encode'

我该如何处理?

这是我的 lib/json_web_token.rb

class JsonWebToken
 class << self
   def encode(payload, exp = 24.hours.from_now)
     payload[:exp] = exp.to_i
     JWT.encode(payload, Rails.application.secrets.secret_key_base)
   end

   def decode(token)
     body = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
     HashWithIndifferentAccess.new body
   rescue
     nil
   end
 end
end

标签: ruby-on-railsrubyauthenticationherokujwt-auth

解决方案


试试这样:

require 'jwt'

class JsonWebToken
 def self.encode(payload, expiration = Rails.application.secrets.jwt_expiration_seconds.to_i.seconds.from_now)
   payload = payload.dup
   payload[:exp] = expiration.to_i
   JWT.encode(payload, Rails.application.secrets.hmac_secret_key)
 end

 def self.decode(token)
   JWT.decode(token, Rails.application.secrets.hmac_secret_key)
 rescue JWT::ExpiredSignature, JWT::DecodeError
   false
 end

 def self.decode_to_payload(token)
   decode(token).first.except('exp').with_indifferent_access
 end
end

我希望这对你有用。


推荐阅读