c# – Server 2 Server Signed Payload Verification JWS


I am trying to validate a JWS token coming from Apple Server, regarding the server 2 server notifications. https://developer.apple.com/documentation/appstoreservernotifications/app_store_server_notifications_v2
What I receive is a JWS with three certificates on the header and no kid header.

I can extract the certificates without problems, but when I try to verify the token, it throws an error saying that the token does not have any kid, which is true.

My question is, how am I supposed to verify this without a kid on the token?

Does anyone have expertise performing this on C#?

This is a part of my current code:

public bool Authorize(Dictionary<string, object> tokenHeaders, string signedPayload)
{
    tokenHeaders.TryGetValue(certsHeader, out var certs);

    var certsList = JsonSerializer.Deserialize<List<string>>(JsonSerializer.Serialize(certs));
    if (certsList.IsNullOrEmpty())
        return false;

    foreach (string certRaw in certsList!)
    {
        var certificateBytes = Encoding.UTF8.GetBytes(certRaw);
        var certificate = new X509Certificate2(certificateBytes);
        if (IsAuthorized(certificate, signedPayload))
            return true;
         
    }

    return false;
}

private bool IsAuthorized(X509Certificate2 certificate, string signedPayload)
{
    try
    {
        _jwtSecurityTokenHandler.ValidateToken(signedPayload, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = false,
            IssuerSigningKey = new X509SecurityKey(certificate),
            ValidateIssuer = false, // apple does not provide issuer or audience.
            ValidateAudience = false,
            
        }, out var result);
        return true;
    }
    catch(Exception e)
    {
        return false;
    }
}

Thank you!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img