For the past couple of days, I’ve been following this article on making my own JWT signatures required for web push notifications to be validated by the push service. Example code is written in JavaScript but I’ve written out a solution within the ASP.NET Core MVC web application to the best of my abilities:
[ActionName("trigger-push-message")]
[HttpPost]
public async Task<IActionResult> triggerPushMessage() {
var first = _context.Subscribers.First();
string jwt_aud, jwt_exp, jwt_sub;
jwt_aud = first.Endpoint.Substring(0,1+first.Endpoint.IndexOf('/',8));
jwt_exp = (((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds() + 12 * 60 * 60).ToString();
jwt_sub = "mailto:[email protected]";
var jwt1 = new {typ = "JWT", alg = "ES256"};
var jwt2 = new {aud = jwt_aud, exp = jwt_exp, sub = jwt_sub};
string base64_1 = Base64Url.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(jwt1)));
string base64_2 = Base64Url.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(jwt2)));
byte[] unsigned_token = Encoding.UTF8.GetBytes(base64_1 + "." + base64_2);
byte[] public_key = Base64Url.Base64UrlDecode("BNIL96_6318XSC6iGF8pOxThvifLMvN5DHtwHwPKSgki0r6QzOvbxGJ6bg6yPu0fJ9aqml-YXpA0UybWvvjeVwc");
byte[] private_key = Base64Url.Base64UrlDecode("gOQ-7RPtxyDdJvMMbc0KrCNyDWaZw60Hmf8T-eHTjqw");
byte[] public_key_x = new byte[32];
byte[] public_key_y = new byte[32];
Array.Copy(public_key, 1, public_key_x, 0, 32);
Array.Copy(public_key, 33, public_key_y, 0, 32);
var ecParameters = new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
D = private_key,
Q =
new ECPoint {
X = public_key_x,
Y = public_key_y,
}
};
using (var ecdsa = ECDsa.Create(ecParameters))
{
// Sign the data
byte[] signatureBytes = ecdsa.SignData(unsigned_token, HashAlgorithmName.SHA256);
// Base64 URL encode the signature
string signature = Base64Url.Base64UrlEncode(signatureBytes);
Console.WriteLine("Signature: " + signature);
Console.WriteLine("JWT: " + base64_1 + "." + base64_2 + "." + signature);
}
return NoContent();
}
And here’s the custom Base64Url encoder and decoder I’ve written up within a class.
public class Base64Url {
public static byte[] Base64UrlDecode(string input)
{
string base64 = input.Replace('-', '+').Replace('_', '/');
switch (base64.Length % 4)
{
case 2: base64 += "=="; break;
case 3: base64 += "="; break;
}
return Convert.FromBase64String(base64);
}
public static string Base64UrlEncode(byte[] input)
{
return Convert.ToBase64String(input)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
}
The private and public keys provided are an example. I am not using these keys.
I got the VAPID keys from this website and inserted it as a string literal as I just want to create a prototype to test out push notifications. I’ve also tried new VAPID keys twice. I did not forget to subscribe with this new key from the client side.
Everything should work correctly, I’ve been reading though the data using the debugger within VSCode. Unfortunately, the JWT returned from the console always returns invalid when I test it out on jwt.io. If I send a web push request to the endpoint through Postman, I get this response (I’ve double checked “Authorization” and “Crypto-Key” headers):
{
"code": 401,
"errno": 109,
"error": "Unauthorized",
"message": "Unknown auth scheme",
"more_info": "http://autopush.readthedocs.io/en/latest/http.html#error-codes"
}
I have also tried using other types of keys by converting the JSON Web Key into PEM formatting using this website to no avail.
Sour Lemon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.