如何在 C# 中使用 APNs Auth Key(.p8 文件)? [英] How to use APNs Auth Key (.p8 file) in C#?
问题描述
我正在尝试使用基于令牌的身份验证向 iOS 设备发送推送通知.
I'm trying to send push notifications to iOS devices, using token-based authentication.
根据需要,我在 Apple 的 Dev Portal 中生成了一个 APNs Auth Key,并下载了它(它是一个扩展名为 p8 的文件).
As required, I generated an APNs Auth Key in Apple's Dev Portal, and downloaded it (it's a file with p8 extension).
要从我的 C# 服务器发送推送通知,我需要以某种方式使用这个 p8 文件来签署我的 JWT 令牌.我该怎么做?
To send push notifications from my C# server, I need to somehow use this p8 file to sign my JWT tokens. How do I do that?
我尝试将文件加载到 X509Certificate2,但 X509Certificate2 似乎不接受 p8 文件,因此我尝试将文件转换为 pfx/p12,但找不到实际可行的方法.
I tried to load the file to X509Certificate2, but X509Certificate2 doesn't seem to accept p8 files, so then I tried to convert the file to pfx/p12, but couldn't find a way to do that that actually works.
推荐答案
我找到了一种方法,使用 BouncyCastle:
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);
}
}
现在创建并签署令牌(使用 jose-jwt):
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);
}
这篇关于如何在 C# 中使用 APNs Auth Key(.p8 文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!