I have developed an App in .NET MAUI which supports Push Notifications. If I send a Push Notification from Apple’s website directly to my physical device, the notification is received and properly processed.
I also have worked on our Push Notification API which sends out notifications to Google’s Firebase and Apple’s APNs depending on what type of device the user is using. I had to rewrite the code for Apple’s Push Notifications as our code was using the endpoint which was supposed to be turned off 2021 but somehow managed to still work in production.
I wrote the class below to send a Push Notification to Apple’s APNs. The development is not final as there are tasks left like storing the token and requesting it every 20-60 minutes. My solution is heavily based on various answers in an older Stack Overflow Thread. I moved it to .NET 8.0, cleaned it up, and applied our coding guidelines.
namespace MyNamespace
{
public class NewApplePushNotificationService : IPushNotificationService
{
private readonly string _url;
private readonly int _port;
private readonly string _certificatePath;
private readonly string _keyId;
private readonly string _bundleId;
private readonly string _teamId;
public NewApplePushNotificationService(bool isProduction, string certificatePath, string keyId, string bundleId, string teamId)
{
_url = isProduction ? "api.push.apple.com" : "api.sandbox.push.apple.com";
_port = 443; // 2197 is also a valid port according to Apple
_certificatePath = certificatePath;
_keyId = keyId;
_bundleId = bundleId;
_teamId = teamId;
}
public async Task Send(string title, string? subtitle, string message, string deviceToken)
{
var notification = new ApplePushNotification()
{
Aps = new ApplePushService()
{
Alert = new Alert(title, subtitle ?? string.Empty, message)
}
};
try
{
var json = JsonConvert.SerializeObject(notification);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Debug.WriteLine($"{this}.Send > {nameof(json)} = {json}");
Debug.WriteLine($"{this}.Send > {nameof(ServicePointManager.SecurityProtocol)} = {ServicePointManager.SecurityProtocol}");
// Get absolute path of the private certificate.
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(directory))
{
Debug.WriteLine($"{this}.Send > Directory "{directory}" does not exist!");
return;
}
var certificatePath = $"{directory}\{_certificatePath}";
if (!File.Exists(certificatePath))
{
Debug.WriteLine($"{this}.Send > File "{certificatePath}" does not exist!");
return;
}
// Get the private key.
ECDsa privateKey;
using (var reader = File.OpenText(certificatePath))
{
var ecPrivateKeyParameters = (ECPrivateKeyParameters)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
var q = ecPrivateKeyParameters.Parameters.G.Multiply(ecPrivateKeyParameters.D).Normalize();
var qx = q.AffineXCoord.GetEncoded();
var qy = q.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
var msEcp = new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = { X = qx, Y = qy }, D = d };
privateKey = ECDsa.Create(msEcp);
}
// Create the authorization token.
var securityKey = new ECDsaSecurityKey(privateKey)
{
KeyId = _keyId
};
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256);
var descriptor = new SecurityTokenDescriptor
{
IssuedAt = DateTime.Now,
// NotBefore = DateTime.UtcNow.AddSeconds(-5),
Issuer = _teamId,
SigningCredentials = credentials
};
var handler = new JwtSecurityTokenHandler();
var encodedToken = handler.CreateEncodedJwt(descriptor);
if (string.IsNullOrEmpty(encodedToken))
{
Debug.WriteLine($"{this}.Send > The creation of the authorization token "{encodedToken}" failed!");
return;
}
Debug.WriteLine($"{this}.Send > {nameof(encodedToken)} = {encodedToken}");
// Send notification to Apple.
var httpClient = new HttpClient
{
DefaultRequestVersion = HttpVersion.Version20,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower
};
var apnsId = Guid.NewGuid().ToString("D");
Debug.WriteLine($"{this}.Send > {nameof(apnsId)} = {apnsId}");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", encodedToken);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-topic", _bundleId);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-push-type", "alert");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-expiration", Convert.ToString(0));
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-priority", Convert.ToString(10));
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-id", apnsId);
// httpClient.DefaultRequestHeaders.TryAddWithoutValidation("apns-collapse-id", "test");
var url = $"https://{_url}:{_port}/3/device/{deviceToken}";
Debug.WriteLine($"{this}.Send > {nameof(url)} = {url}");
var response = await httpClient.PostAsync(new Uri(url), new StringContent(json, Encoding.UTF8, "application/json"));
if (response == null)
{
Debug.WriteLine($"{this}.Send > Invalid response object.");
return;
}
Debug.WriteLine($"{this}.Send > {nameof(response)} = {response} (Code {response.StatusCode})");
Debug.WriteLine($"{this}.Send > {nameof(response.IsSuccessStatusCode)} = {response.IsSuccessStatusCode}");
if (response.IsSuccessStatusCode)
{
try
{
var responseContent = await response.Content.ReadAsStringAsync();
Debug.WriteLine($"{this}.Send > {nameof(responseContent)} = {responseContent}");
}
catch (Exception exception)
{
Debug.WriteLine($"{this}.Send > Reading content failed. {nameof(exception)} = {exception}");
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
}
}
}
}
The “problem” that I have is that executing the code works in that regards that Apple tells me everything is okay. I get a 200 status code in the response. No exceptions are raised and the response object even mirrors the ASPN Id I send in the header.
But I do not get a Push Notification on my phone. Again, if I send one from the website, it works. Using the same information (like Device Token, payload, etc.).
MyNamespace.NewApplePushNotificationService.Send > json = {"Aps":{"Alert":{"Title":"My title","Subtitle":"My subtitle","Body":"My body"}}}
MyNamespace.NewApplePushNotificationService.Send > SecurityProtocol = Tls12
MyNamespace.NewApplePushNotificationService.Send > encodedToken = REDACTED
MyNamespace.NewApplePushNotificationService.Send > apnsId = 4fbf3ef3-6120-4f34-a3ea-0cd648e2cc69
MyNamespace.NewApplePushNotificationService.Send > url = https://api.sandbox.push.apple.com:443/3/device/REDACTED
MyNamespace.NewApplePushNotificationService.Send > response = StatusCode: 200, ReasonPhrase: 'OK', Version: 2.0, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
apns-id: 4fbf3ef3-6120-4f34-a3ea-0cd648e2cc69
apns-unique-id: 92f6386c-e17a-1add-a09e-aeae5d047ade
} (Code OK)
MyNamespace.NewApplePushNotificationService.Send > IsSuccessStatusCode = True
MyNamespace.NewApplePushNotificationService.Send > responseContent =
In case someone wonders: The reason I explicitly set the TLS to 1.2 is because I wanted to make absolutely sure during my tests, that not a silly reason like an older default TLS hinders the success of the call.
If anyone sees a flaw or has an idea what I could have done wrong, please let me know. The fact that I can receive and handle Push Notifications in my phone when sent from Apple’s website means the phone is handling them well (permissions, events, etc.). The fact that Apple confirms my Push Notification call from the API with 200 means, Apple says it’s fine. But something clearly is wrong and I am confused.