How to generate JWT signed token using keyId using JWS header in c#

676 Views Asked by At

User redirected to my website throw a redirected url from a thirdparty website, I wanted to verify that redirected URL, the thirdparty signs the redirected url using RSA private key using RS256 algorithm then put it as a signature in the url. The redirected url look like:

string redirectUrl = "https://my-domain.com/landservicecallback?state=abcd1234&dealId=xyz5678&expireOn=2006-09-18T00:00:00.000Z&signature=VGhpcyBpcyBhIHNpZ25hdHVyZSB0byB2ZXJ5IHRoaXMgaW5zdGFuY2U%3D&keyId=%3MvJikN0EgR5vNplYFZR50z2G******";

Third Party provided me a documentation(documenation using Nimbus Java lib but I want it in c#) regarding how they want me to verify the signature by generating a signed JWT token from the given redirected url params and a public key.

so what I am doing is below:

first generating JWtPayload from the redirected url data:

        // Set up the JWT payload
        var claims = new[]
        {
            new Claim("partnerUrl", "https://www.my-domain.com"),
            new Claim("dealId", "testDealId"),
            new Claim("expireOn", "2023-02-18T00:00:00.000Z"),
        };
        var payload = new JwtPayload(claims);

After that the documentation asked me to generate JWSHeader with JWSAlgorithm.RS256 and keyId(attached in redirected url, note: its not the public key). This is where I got stuck actually, I can't seems to find a way to replicate following code in my c#

// create JWS header
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(keyId).build();

// create JWT object
 SignedJWT signedJWT = new SignedJWT(jwsHeader, payload);

I saw a similar lib jose-jwtfor c# but it returns JWT token by providing public key but can't able to do like above.

Note: Also the documentation mentioned that after I got signed JWT object in above steps I need to use public key to build a jwsVerifier and verify the signature given in the url like below:

// create verifier
JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPublicKey);
try {
valid = jwsVerifier.verify(jwsHeader, signedJWT.getSigningInput(), new Base64URL(signature));
} catch (JOSEException e) {
   throw new RuntimeException("Failed to verify signature", e);
}

This encryption mechanism completely new to me so I might be missing to make a workaround in c# for the above code. Any suggestion how can I achieve above solution in c# dot net?

0

There are 0 best solutions below