Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '9.x'
dotnet-version: '10.x'

- name: Restore
run: dotnet restore CorePush.sln
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '9.x'
dotnet-version: '10.x'

- name: Restore
run: dotnet restore CorePush.sln
Expand Down
3 changes: 1 addition & 2 deletions CorePush.Tester/CorePush.Tester.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand All @@ -11,7 +11,6 @@

<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="3.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>

</Project>
16 changes: 7 additions & 9 deletions CorePush.Tester/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,13 @@ private static async Task SendApnNotificationAsync()
ServerType = apnServerType,
};

while (true)
{
var apn = new ApnSender(settings, http);
var payload = new AppleNotification(
Guid.NewGuid(),
"Hello World (Message)",
"Hello World (Title)");
var response = await apn.SendAsync(payload, apnDeviceToken);
}
var apn = new ApnSender(settings, http);
var payload = new AppleNotification(
Guid.NewGuid(),
"Hello World (Message)",
"Hello World (Title)");
var response = await apn.SendAsync(payload, apnDeviceToken);
Console.WriteLine($"APN Response: {response.StatusCode} - {response.Message}");
}

private static async Task SendFirebaseNotificationAsync()
Expand Down
59 changes: 27 additions & 32 deletions CorePush/Apple/ApnSender.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
Expand All @@ -7,8 +7,6 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

using CorePush.Interfaces;
using CorePush.Models;
Expand Down Expand Up @@ -43,7 +41,7 @@ public class ApnSender : IApnSender
public ApnSender(ApnSettings settings, HttpClient http) : this(settings, http, new DefaultCorePushJsonSerializer())
{
}

/// <summary>
/// Apple push notification sender constructor
/// </summary>
Expand All @@ -55,7 +53,7 @@ public ApnSender(ApnSettings settings, HttpClient http, IJsonSerializer serializ
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.http = http ?? throw new ArgumentNullException(nameof(http));
this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));

if (http.BaseAddress == null)
{
http.BaseAddress = new Uri(servers[settings.ServerType]);
Expand All @@ -65,7 +63,7 @@ public ApnSender(ApnSettings settings, HttpClient http, IJsonSerializer serializ
/// <summary>
/// Serialize and send notification to APN. Please see how your message should be formatted here:
/// https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1
/// !IMPORTANT: If you send many messages at once, make sure to retry those calls. Apple typically doesn't like
/// !IMPORTANT: If you send many messages at once, make sure to retry those calls. Apple typically doesn't like
/// to receive too many requests and may occasionally respond with HTTP 429. Just try/catch this call and retry as needed.
/// </summary>
/// <exception cref="HttpRequestException">Throws exception when not successful</exception>
Expand All @@ -78,14 +76,16 @@ public async Task<PushResult> SendAsync(
ApnPushType apnPushType = ApnPushType.Alert,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(deviceToken);

var path = $"/3/device/{deviceToken}";
var json = serializer.Serialize(notification);

using var message = new HttpRequestMessage(HttpMethod.Post, path);

message.Version = new Version(2, 0);
message.Content = new StringContent(json);

message.Headers.Authorization = new AuthenticationHeaderValue("bearer", GetJwtToken());
message.Headers.TryAddWithoutValidation(":method", "POST");
message.Headers.TryAddWithoutValidation(":path", path);
Expand All @@ -100,21 +100,22 @@ public async Task<PushResult> SendAsync(
}

using var response = await http.SendAsync(message, cancellationToken);

var content = await response.Content.ReadAsStringAsync(cancellationToken);
var error = response.IsSuccessStatusCode
? null
: serializer.Deserialize<ApnsError>(content).Reason;
var error = response.IsSuccessStatusCode
? null
: serializer.Deserialize<ApnsError>(content)?.Reason;

return new PushResult((int)response.StatusCode, response.IsSuccessStatusCode, content, error);
}

private string GetJwtToken()
{
var (token, date) = tokens.GetOrAdd(settings.AppBundleIdentifier, _ => new Tuple<string, DateTime>(CreateJwtToken(), DateTime.UtcNow));
var cacheKey = $"{settings.AppBundleIdentifier}:{settings.P8PrivateKeyId}";
var (token, date) = tokens.GetOrAdd(cacheKey, _ => new Tuple<string, DateTime>(CreateJwtToken(), DateTime.UtcNow));
if (date < DateTime.UtcNow.AddMinutes(-tokenExpiresMinutes))
{
tokens.TryRemove(settings.AppBundleIdentifier, out _);
tokens.TryRemove(cacheKey, out _);
return GetJwtToken();
}

Expand All @@ -129,32 +130,26 @@ private string CreateJwtToken()
var payloadBase64 = Base64UrlEncode(payload);
var unsignedJwtData = $"{headerBase64}.{payloadBase64}";
var unsignedJwtBytes = Encoding.UTF8.GetBytes(unsignedJwtData);

var privateKeyBytes = Convert.FromBase64String(CryptoHelper.CleanP8Key(settings.P8PrivateKey));
var keyParams = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privateKeyBytes);
var q = keyParams.Parameters.G.Multiply(keyParams.D).Normalize();

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

var signature = dsa.SignData(unsignedJwtBytes, 0, unsignedJwtBytes.Length, HashAlgorithmName.SHA256);

using var dsa = ECDsa.Create();
dsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);

var signature = dsa.SignData(unsignedJwtBytes, HashAlgorithmName.SHA256);
var signatureBase64 = Base64UrlEncode(signature);
return $"{unsignedJwtData}.{signatureBase64}";
}

private static string Base64UrlEncode(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
return Base64UrlEncode(bytes);
}

private static string Base64UrlEncode(byte[] bytes) => Convert.ToBase64String(bytes);
private static string Base64UrlEncode(byte[] bytes) =>
Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.TrimEnd('=');
}
15 changes: 10 additions & 5 deletions CorePush/CorePush.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>

<Title>Server Side library for sending ✅Web, ✅Android and ✅iOS Push Notifications</Title>
Expand All @@ -25,6 +25,15 @@
<PackageTags>push-notifications android-push-notifications ios-push-notifications web-push web-push-notifications apn fcm firebase</PackageTags>

<PackageReleaseNotes>
v5.0.0
- Remove BouncyCastle dependency in favor of built-in .NET cryptography
- Upgrade to .NET 10
- Fix Base64URL encoding for JWT tokens (RFC 7617)
- Fix null reference in APN error handling
- Fix token cache key collision
- Add device token validation
- Propagate CancellationToken in Firebase sender

v4.3.0, v4.4.0
- Upgrade to Bouncycastle.Cryptography
- Other pkg version bumps
Expand Down Expand Up @@ -81,10 +90,6 @@ v3.0.0

</PropertyGroup>

<ItemGroup>
<PackageReference Include="BouncyCastle.Cryptography" Version="2.6.2" />
</ItemGroup>

<ItemGroup>
<None Include="..\Icon.png" Pack="true" PackagePath="Icon.png" />
<None Include="..\README.md" Pack="true" PackagePath="README.md" />
Expand Down
Loading
Loading