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

后端 未结 1 728
慢半拍i
慢半拍i 2021-01-11 11:48

I\'m trying to send push notifications to iOS devices, using token-based authentication.

As required, I generated an APNs Auth Key in Apple\'s Dev Portal, and downlo

相关标签:
1条回答
  • 2021-01-11 12:12

    I found a way to do that, using 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);
        }
    }
    

    And now creating and signing the token (using 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);
    }
    
    0 讨论(0)
提交回复
热议问题