简体   繁体   English

jwk = JWT::JWK.import(keyHash) *** ArgumentError 异常:无效 base64

[英]jwk = JWT::JWK.import(keyHash) *** ArgumentError Exception: invalid base64

I'm trying to do te backend apple login and it looks work good until the line jwk = JWT::JWK.import(keyHash) it's always return the error invalid base64.我正在尝试进行后端苹果登录,它看起来很好,直到jwk = JWT::JWK.import(keyHash)行它总是返回错误无效 base64。 I'm using the gem jwt version 2.2.1 and Ruby 2.2.4我正在使用 gem jwt 版本 2.2.1 和 Ruby 2.2.4

begin
  header_segment = JSON.parse(Base64.decode64(jwt.split(".").first))
  alg = header_segment["alg"]
  kid = header_segment["kid"]

  apple_response = Net::HTTP.get(URI.parse(GET_PK_APPLE_URL))
  apple_certificate = JSON.parse(apple_response)

  keyHash = ActiveSupport::HashWithIndifferentAccess.new(apple_certificate["keys"].select {|key| key["kid"] == kid}[0])

  jwk = JWT::JWK.import(keyHash)

  token_data = JWT.decode(jwt, jwk.public_key, true, {algorithm: alg})[0]

  if token_data.has_key?("sub") && token_data.has_key?("email") && userIdentity == token_data["sub"]
    puts "Name: " + name + " is validated."
    login_or_create_user('apple')
  else
    render_error
  end
rescue StandardError => e
  render_error
end

I found the problem, the jwt gem has a openssl dependency and the openssl needs a more actual version from Ruby, I couldn't change my Ruby version now for other reasons so I needed to change my code to get the JWK without use ```JWT::JWK.import(keyHash)````. I found the problem, the jwt gem has a openssl dependency and the openssl needs a more actual version from Ruby, I couldn't change my Ruby version now for other reasons so I needed to change my code to get the JWK without use `` `JWT::JWK.import(keyHash)```。 I also needed to user the UrlSafeBase64 gem.我还需要使用 UrlSafeBase64 gem。

begin      
  header_segment = JSON.parse(Base64.decode64(jwt.split(".").first))
  alg = header_segment["alg"]
  kid = header_segment["kid"]

  apple_response = Net::HTTP.get(URI.parse(LOGIN_APPLE_URL))
  apple_certificate = JSON.parse(apple_response)

  keyHash = ActiveSupport::HashWithIndifferentAccess.new(apple_certificate["keys"].select {|key| key["kid"] == kid}[0])      
  key = OpenSSL::PKey::RSA.new
  key.e = OpenSSL::BN.new(UrlSafeBase64.decode64(keyHash["e"]), 2)
  key.n = OpenSSL::BN.new(UrlSafeBase64.decode64(keyHash["n"]), 2)
                  
  token_data = JWT.decode(jwt, key, true, {algorithm: alg})[0]
  
  if token_data.has_key?("sub") && token_data.has_key?("email") && userIdentity == token_data["sub"]        
    login_or_create_user('apple')
  else
    render_error
  end
rescue StandardError => e
  render_error
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM