ruby 正在为App Store Connect API生成令牌

u5i3ibmn  于 2023-03-01  发布在  Ruby
关注(0)|答案(4)|浏览(207)

我需要为Store Connect API生成JWT标记。我正在尝试使用jwt ruby gem ruby-jwt。这是我的标记生成代码,

payload = {
      'iss': my_issuer_id_from_db,
      'exp': generated_unix_timestamp, #Time.now + 20min
      'aud': 'hard_coded_string_from_doc'
  }
  header = {
      'alg': 'ES256',
      'kid': my_key_id_from_db,
      'typ': 'JWT'
  }

private_key = OpenSSL::PKey.read(File.read('/tmp/private_key.pem'))
# private_key - <OpenSSL::PKey::EC:0x000000000XXXXXXX>

@token = JWT.encode(payload, private_key, 'ES256', header)
# encoded_header.encoded_payload.emcoded_signature

我将此令牌放入请求的标题中:

headers = { Authorization: 'Bearer' + @token }

我收到答复如下:

"errors": [{
                "status": "401",
                "code": "NOT_AUTHORIZED",
                "title": "Authentication credentials are missing or invalid.",
                "detail": "Provide a properly configured and signed bearer token, and make sure that it has not expired. Learn more about Generating Tokens for API Requests https://developer.apple.com/go/?id=api-generating-tokens"
        }]
}

我认为问题出在令牌上(直接使用签名)。当我尝试使用online tool解码令牌时,我的有效负载和报头被正确解码。状态:无效签名
我做错了什么?知道怎么做才合适吗?

7d7tgy0s

7d7tgy0s1#

我遇到了类似的身份验证错误,即 NOT_AUTHORIZED。我通过以下步骤解决了该错误:

1.创建Ruby脚本文件以生成有效的Bearer令牌:

require "base64"
require "jwt"
ISSUER_ID = "YOUR_ISSUER_ID"
KEY_ID = "YOUR PRIVATE KEY ID"    // this is ID part from downloaded .p8 file name (see below for ref.)
private_key = OpenSSL::PKey.read(File.read(path_to_your_private_key/AuthKey_#{KEY_ID}.p8))   // you can enclose your file path in quotes if needed, and can pass here totally static file path (here we are reusing Key_ID variable)

token = JWT.encode(
   {
    iss: ISSUER_ID,
    exp: Time.now.to_i + 20 * 60,
    aud: "appstoreconnect-v1"
   },
   private_key,
   "ES256",
   header_fields={
       kid: KEY_ID }
)
puts token

然后在Mac上使用以下命令运行此脚本。
$ ruby jwt.rb
这将在您的终端屏幕上显示一个有效的Bearer令牌,您可以在下一步中使用它。

  • 备注:*
  • 为了运行上面的脚本,您需要安装ruby
  • 你将从开发者帐户复制颁发者ID。如果没有,请生成一个。
  • 请确保您使用的是经过身份验证的用户的“.p8”证书,这意味着您下载“.p8”证书的帐户应该具有执行API级别操作的权限。对于我的情况,我使用了 Admin 类型的帐户。最初我使用的是 Developer 类型的用户帐户,当我进行最后的Curl调用以获取令牌时,它一直给我 Not_Authorized 错误。

2.使用令牌:

现在,我们已经了解了如何生成令牌来访问App Store Connect API,我们可以通过传递授权头来使用它。例如,获取我们可以使用的所有用户的列表

$ curl  https://api.appstoreconnect.apple.com/v1/users --Header "Authorization: Bearer lOOOOOOOOOOOONG_GENERATED_TOKEN"

这将列出App Store Connect的所有用户。请记住,我们必须在每次请求时使用此令牌,并且我们必须每隔20分钟创建一个新令牌。

gc0ot86w

gc0ot86w2#

传入的授权字符串中缺少空格。将代码修改为后,代码工作正常
headers = { Authorization: 'Bearer ' + @token }

hzbexzde

hzbexzde3#

我刚刚在这里创建了python3版本。401 Authentication credentials are missing or invalid可能与获取时间issuedexpired有关。
检查你的函数获取时间是苹果推荐的UNIX epoch time

import jwt
import datetime as dt

key_id = '#####' 
alg = 'ES256'
typ = 'JWT'
issue_id = '##########################'
aud = 'appstoreconnect-v1'

# Define issue timestamp.
issued_at_timestamp = int(dt.datetime.now().timestamp())
# Define expiration timestamp. May not exceed 20 minutes from issue timestamp.
expiration_timestamp = issued_at_timestamp + 20*60

# Define JWT headers.
headers = dict()
headers['alg'] = alg
headers['kid'] = key_id
headers['typ'] = typ

# Define JWT payload.
payload = dict()
payload['iss'] = issue_id
payload['iat'] = issued_at_timestamp
payload['exp'] = expiration_timestamp
payload['aud'] = aud

# Path to signed private key.
KEY_FILE = '#########.p8' 

with open(KEY_FILE,'r') as key_file:
     key = ''.join(key_file.readlines())

client_secret = jwt.encode(
payload=payload,  
headers=headers,
algorithm=alg,  
key=key
)

with open('client_secret.txt', 'w') as output: 
     output.write(client_secret)
    
    
# Usage, after run this code by python3
# get token from `client_secret.txt` and replace to [signed token]
# Remember expired time maximum is 20 minutes
#
# curl -v -H 'Authorization: Bearer [signed token]' "https://api.appstoreconnect.apple.com/v1/apps"
#
# More detail https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests
w6mmgewl

w6mmgewl4#

我有一个2023年的答案,它利用了@Nah的答案中的Ruby脚本,但对我来说很有效,因为它添加了一些旧答案中缺少的键。
Ruby脚本:

require "base64"
require "jwt"
ISSUER_ID = "YOUR-ISSUER-ID"
KEY_ID = "YOUR-KEY-ID"
private_key = OpenSSL::PKey.read(File.read("PATH_TO_KEY_DOWNLOADED_FROM_APP_STORE_CONNECT.p8"))
token = JWT.encode(
  {
    iss: ISSUER_ID,
    exp: Time.now.to_i + 20 * 60,
    aud: "appstoreconnect-v1",
    bid: "YOUR_BUNDLE_ID"
  },
  private_key,
  "ES256",
  header_fields = {
    alg: "ES256",
    kid: KEY_ID,
    typ: "JWT"
  }
)
puts token

然后,您可以在与Apple通信时将该密钥放在Authorization标头中。
例如,我需要从Apple获得应用内购买事件的测试通知,这样我就可以将令牌放在curl请求中并获得200:

curl -v --request POST \
-H "Authorization: Bearer YOUR_LONG_TOKEN_HERE" \
"https://api.storekit-sandbox.itunes.apple.com/inApps/v1/notifications/test"

如果希望使用Postman,请在Authorization选项卡中,将Ruby脚本生成的标记设置为Bearer Token

相关问题