如何在 C# 中使用 APNs 授权密钥(.p8 文件)?

How to use APNs Auth Key (.p8 file) in C#?

我正在尝试使用基于令牌的身份验证向 iOS 设备发送推送通知。

根据需要,我在Apple的Dev Portal中生成了一个APNs Auth Key,并下载了它(它是一个扩展名为p8的文件)。

要从我的 C# 服务器发送推送通知,我需要以某种方式使用此 p8 文件来签署我的 JWT 令牌。我该怎么做?

我尝试将文件加载到 X509Certificate2,但 X509Certificate2 似乎不接受 p8 文件,所以我尝试将文件转换为 pfx/p12,但找不到方法确实有效。

我找到了一种方法,使用 BouncyCastle:

private static CngKey GetPrivateKey()
{
    using (var reader = File.OpenText("path/to/apns/auth/key/file.p8"))
    {
        var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
        var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
        var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
        return EccKey.New(x, y, d);
    }
}

现在创建并签署令牌(使用 jose-jwt):

private static string GetProviderToken()
{
    var epochNow = (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
    var payload = new Dictionary<string, object>()
    {
        {"iss", "your team id"},
        {"iat", epochNow}
    };
    var extraHeaders = new Dictionary<string, object>()
    {
        {"kid", "your key id"}
    };
    var privateKey = GetPrivateKey();
    return JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, extraHeaders);
}

我希望这是一个解决方案;

private static string GetToken(string fileName)
    {
        var fileContent = File.ReadAllText(fileName).Replace("-----BEGIN PRIVATE KEY-----", "").Replace
            ("-----END PRIVATE KEY-----", "").Replace("\r", "");
        
        var signatureAlgorithm = GetEllipticCurveAlgorithm(fileContent);

        ECDsaSecurityKey eCDsaSecurityKey = new ECDsaSecurityKey(signatureAlgorithm)
        {
            KeyId = "S********2"
        };

        var handler = new JwtSecurityTokenHandler();   
        JwtSecurityToken token = handler.CreateJwtSecurityToken(
            issuer: "********-****-****-****-************",
            audience: "appstoreconnect-v1",
            expires: DateTime.UtcNow.AddMinutes(5), 
            issuedAt: DateTime.UtcNow,
            notBefore: DateTime.UtcNow,
            signingCredentials: new SigningCredentials(eCDsaSecurityKey, SecurityAlgorithms.EcdsaSha256));

        return token.RawData;

    }
    
    private static ECDsa GetEllipticCurveAlgorithm(string privateKey)
    {
        var keyParams = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

        var normalizedEcPoint = keyParams.Parameters.G.Multiply(keyParams.D).Normalize();

        return ECDsa.Create(new ECParameters
        {
            Curve = ECCurve.CreateFromValue(keyParams.PublicKeyParamSet.Id),
            D = keyParams.D.ToByteArrayUnsigned(),
            Q =
            {
                X = normalizedEcPoint.XCoord.GetEncoded(),
                Y = normalizedEcPoint.YCoord.GetEncoded()
            }
        });
    }