将 ES256 算法与 jwt-dotnet 一起用于 Apple AppStore

Using ES256 algorithm with jwt-dotnet for Apple AppStore

我正在尝试生成一个 jwt 令牌以连接到 AppStore API。我正在使用 jwt-dotnet 库来执行此操作。

Apple 要求使用 ES256,而 jwt-dotnet 要求 public 密钥来完成这项工作。我只从 AppStore 下载了一个私钥。我该如何处理?

这是我的代码:

public static string GenerateAppStoreJwtToken()
{
   var header = new Dictionary<string, object>()
   {
      { "kid", "MY_VALUE" },
      { "typ", "JWT" }
   };

   var scope = new string[1] { "GET /v1/apps?filter[platform]=IOS" };
   var payload = new Dictionary<string, object>
   {
      { "iss", "MY_VALUE" },
      { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
      { "exp", DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeSeconds() },
      { "aud", "appstoreconnect-v1" },
      { "scope", scope }
   };


   IJwtAlgorithm algorithm = new ES256Algorithm(???); // What am I going to use here?
   IJsonSerializer serializer = new JsonNetSerializer();
   IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
   IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

   var token = encoder.Encode(header, payload, privateKey);

   return token;
}

这是对我有用的最终解决方案。我最终切换到 jose-jwt,但我很确定您可以使用 jwt-dotnet 处理同样的事情。我刚刚发现使用 jose-jwt 更容易一些。这是 link 到 jose-jwthttps://github.com/dvsekhvalnov/jose-jwt

这是最终代码。请注意,我确实使用了我在 p8 文件中找到的私钥,并且不需要转换任何东西。所以我传递给 GenerateAppStoreJwtToken() 函数的 privateKey 参数直接来自 p8 文件。

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Jose;
    
public static string GenerateAppStoreJwtToken(string privateKey)
{
    var header = new Dictionary<string, object>()
    {
        { "alg", "ES256" },
        { "kid", "MY_VALUE" },
        { "typ", "JWT" }
    };
    
    var scope = new string[1] { "GET /v1/apps?filter[platform]=IOS" };
    var payload = new Dictionary<string, object>
    {
        { "iss", "MY_VALUE" },
        { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
        { "exp", DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() },
        { "aud", "appstoreconnect-v1" },
        { "scope", scope }
    };
    
    CngKey key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);

    string token = JWT.Encode(payload, key, JwsAlgorithm.ES256, header);
 
    return token;
}