Ruby on rails 如何修复错误TypeError(没有将nil隐式转换为字符串):lib/json_web_token.rb:5:in`encode';?
我有一个简单的Jwt身份验证可以在本地环境中完美工作,但是当上传到heroku时会出现以下错误 TypeError(没有将nil隐式转换为字符串):lib/json_web_token.rb:5:in`encode' 我该怎么处理这件事 这是我的lib/json\u web\u token.rbRuby on rails 如何修复错误TypeError(没有将nil隐式转换为字符串):lib/json_web_token.rb:5:in`encode';?,ruby-on-rails,ruby,authentication,heroku,jwt-auth,Ruby On Rails,Ruby,Authentication,Heroku,Jwt Auth,我有一个简单的Jwt身份验证可以在本地环境中完美工作,但是当上传到heroku时会出现以下错误 TypeError(没有将nil隐式转换为字符串):lib/json_web_token.rb:5:in`encode' 我该怎么处理这件事 这是我的lib/json\u web\u token.rb class JsonWebToken class << self def encode(payload, exp = 24.hours.from_now) payload[
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
类JsonWebToken
class试着这样做:
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
我希望这对您有用。在编码
和解码
方法中将Rails.application.secrets.secret\u key\u base
替换为ENV['secret\u key\u base']
Heroku应该已经自动设置了SECRET\u KEY\u BASE
环境变量。您可以通过在CLI中运行以下命令来确保:
heroku config:get SECRET_KEY_BASE
如果未设置,可以通过以下方式进行设置:
heroku config:set SECRET_KEY_BASE=$(rake secret)
有效负载或Rails.application.secrets.secret\u key\u base为零。在Rails 5.3中,Rails.application.secrets.secret_key_base已成为Rails.application.credentials.secret_key_base。你是否在本地和Heroku上使用了相同版本的rails?我尝试了这两种语句,但仍然得到相同的错误!您可以通过添加一些代码来产生一个更具体的错误,从而确定哪个是零,然后您将有更多的工作要做。类似于:raise StandardError.new(“有效负载为零”)除非有效负载/raise StandardError.new(“密钥为零”)除非Rails.application.secrets.secret\u key\u base。这不会修复您的代码,但会给您一个更具体的错误