使用 Ruby 为 iTunes Connect API 生成 JWT

Generating JWT with Ruby for iTunes Connect API

我正在尝试生成一个令牌来签署我对 iTunes Connect 的请求 API。那是我的 Ruby 文件:

require "jwt"
require 'openssl'

ISSUER_ID = "my issuer string"
KEY_ID = "my key id string"

key_file = File.read('my p8 file containing my private key') # Located at the same folder than my ruby file
private_key = OpenSSL::PKey::RSA.new(key_file)

payload = {
      'iss': ISSUER_ID,
      'exp': 1528408800,
      'aud': 'appstoreconnect-v1'
  }

header = {
      'alg': 'ES256',
      'kid': KEY_ID,
      'typ': 'JWT'
  }

  jwt = JWT.encode(payload, private_key, algorithm='ES256', header)
  puts jwt

如果我 运行 这个文件 ruby jwt.rb 我得到以下输出:

/Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt/algos/ecdsa.rb:15:in sign': undefined method group' for # (NoMethodError) from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt/signature.rb:35:in sign' from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt/encode.rb:39:in encoded_signature' from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt/encode.rb:47:in encode_segments' from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt/encode.rb:20:in initialize' from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt.rb:21:in new' from /Library/Ruby/Gems/2.3.0/gems/jwt-2.1.0/lib/jwt.rb:21:in encode' from jwt.rb:22:in '

从控制台输出很难判断出什么问题,但如果我使用 RS256 作为算法并省略 header,脚本会成功生成令牌。

好像是使用RSA密钥和ECDSA加密算法导致的。使用 RS256 算法而不是 ES256,或者使用 OpenSSL::PKey::EC 而不是 OpenSSL::PKey::RSA(不过你可能需要一个新的私钥)。

Apnoticgem,它以现代Apple方式实现Apple推送通知:
HTTP2.0 + JWT + p8.

或许,您可以在其 ProviderToken class 中找到解决方案。