2

I am trying to call the Apple DeviceCheck API from an ASP.NET Core API. To do so I need to create a JWT. I use Jose and BouncyCastle lib for that. I tried 2 different key creations and got each time a 401 (Unable to verify authorization token) HTTP status back from the DeviceCheck development v1 API.

private const string MembershipTeamId = "QWERTYUIOP";
private const string P8KeyId = "QWERTYUIOP";

public static string CreateJwt()
{
    var extraHeaders = new Dictionary<string, object>()
    {
        { "kid", P8KeyId },
        { "typ", "JWT" }
    };

    var payload = new Dictionary<string, object>()
    {
        { "iss", MembershipTeamId },
        { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() }
    };

    var key = GetCngKey();

    return JWT.Encode(payload, key, JwsAlgorithm.ES256, extraHeaders);
}

Below 2 different methods, I tried to create the CngKey

// using BouncyCastle
private static CngKey GetCngKey()
{
    using (var reader = System.IO.File.OpenText(@"C:\pathto\key.p8"))
    {
        var param = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        return EccKey.New(
            param.Parameters.G.AffineXCoord.GetEncoded(),
            param.Parameters.G.AffineYCoord.GetEncoded(),
            param.D.ToByteArrayUnsigned());
    }
}

// using CngKey
private static CngKey GetCngKey2()
{
    var keyBytes = Convert.FromBase64String("inline .p8 content without -----BEGIN/END PRIVATE KEY-----");
    return CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob);
}
Ulysse
  • 41
  • 6

0 Answers0