I'm trying to do a proof of concept validating a json web token asymmetrically in c#. I'm currently trying the Json Web Token Handler for Microsoft.NET library, but I'm struggling to get it to work. The documentation is limited, and most posts online are either issuing tokens or validating tokens symmetrically. I was able to symmetrically validate a token using the generic JWT library as described in this post, but the solution provided there does not handle asymmetric validation, based on the way the decode function is written.
Here is the code I'm working with:
var jwtHandler = new JwtSecurityTokenHandler();
var certificate = new X509Certificate2(certpath, "password", X509KeyStorageFlags.Exportable);
var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
if (privateKey == null)
{
throw new Exception("Not an RSA private key");
}
var cspBlob = privateKey.ExportCspBlob(true);
var pk = Convert.ToBase64String(cspBlob);
//This code also works instead of the above code, I believe
//var privateKey = certificate.Export(X509ContentType.Pfx);
var tokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = "exampleAudience",
ValidIssuer = "exampleIssuer",
IssuerSigningToken = pk
};
//The token passed in here is a string version of the token
//I have tried both a JWTSecurityToken token and just a string version
ClaimsPrincipal claimsPrincipal = jwtHandler.ValidateToken(asymmetricToken, tokenValidationParameters);
if (claimsPrincipal != null)
{
// Valid
Console.Write("Valid!");
}
I'm getting a couple of errors, namely in the tokenValidationParameters section and the Validate token method. I'm just not sure how these functions work with respect to my scenario. What validation parameters do I need to set? Also, I see on the msdn page that there is an overloaded method that takes a token and validation parameters, but I'm getting a compilation error indicating that no version of this method takes 2 parameters.
Lastly, does anyone know if this code will actually work for asymmetric validation, or does the ValidateToken method on JWTHandler only work for symmetric validation?
Any help at all would be appreciated. Thanks.