'Flutter jsonwebtoken generate Appstore Connect API token invalid

I am trying to generate a Appstore Connect API token to manage my apps. The package I am using is dart_jsonwebtoken. The code:

final jwt = JWT({
    "iss": "YOUR_ISSUER_ID",
    "iat": DateTime.now().millisecondsSinceEpoch / 1000,
    "exp": DateTime.now().add(Duration(days: 30)).millisecondsSinceEpoch / 1000,
    "aud": "appstoreconnect-v1",
    "scope": [
      "GET /v1/apps?filter[platform]=IOS"
    ]
  }, header: {
    "alg": "ES256",
    "kid": "YOUR PRIVATE KEY ID",
    "typ": "JWT"
  });

  // Here I use the content from AuthKey_KEYID.p8 file
  final token = jwt.sign(ECPrivateKey('''-----BEGIN PRIVATE KEY-----
  YOUR AuthKey Content
  -----END PRIVATE KEY-----'''), algorithm: JWTAlgorithm.ES256);

  print('Signed token: $token\n');

The token is generated successfully, and I am using it to call the API, but I am getting an invalid token error:

{
    "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"
        }
    ]
}

I am pretty sure there is some wrong with my code to generate the token. Can somebody help me with that? Thanks in advance.

I got it working by using below ruby code. The generated token is working fine. I am trying to rewrite it using flutter.

require "base64"
require "jwt"
ISSUER_ID = "2ece1127-df4d-426a-a3eb-061e68f5eebe"
KEY_ID = "W9M2AM584Y"
private_key = OpenSSL::PKey.read(File.read('AuthKey_W9M2AM584Y.p8'))
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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source