Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying a JWT using the public key with C#

Tags:

c#

.net

jwt

azure

I am building a React app backed by Azure functions written in C#. I've implemented JWT authentication via Userfront which is working fine on the front end but I'm struggling to verify the token using the public key in the functions.

I've tried numerous approaches, JWT-DotNet being the most recent but to no avail.

Can anyone please provide a working code example?

Here is what I have currently (which errors when creating the new RS256Algorithm with "Cannot find the requested object."):

var headers = req.Headers;
if (!headers.TryGetValue("Authorization", out var tokenHeader))
   return new StatusCodeResult(StatusCodes.Status403Forbidden);

var token = tokenHeader[0].Replace("Bearer ", "");

var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("Userfront_PublicKey"));

var urlEncoder = new JwtBase64UrlEncoder();
var publicKey = urlEncoder.Encode(plainTextBytes);

try
{
   IJsonSerializer serializer = new JsonNetSerializer();
   var provider = new UtcDateTimeProvider();
   IJwtValidator validator = new JwtValidator(serializer, provider);
   IJwtAlgorithm algorithm = new RS256Algorithm(new X509Certificate2(plainTextBytes));
   IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder,algorithm);

   var json = decoder.Decode(token[0], publicKey, verify: true);
}
catch (TokenExpiredException)
   ...
catch (SignatureVerificationException)
   ...
like image 985
DiscoStu1975 Avatar asked Nov 06 '22 01:11

DiscoStu1975


1 Answers

Assuming that the environment variable "Userfront_PublicKey" contains a PEM-encoded RSA public key, i.e.:

-----BEGIN RSA PUBLIC KEY-----
(your base64-encoded RSA public key)
-----END RSA PUBLIC KEY-----

then I would try the following (not tested, sorry):

var headers = req.Headers;
if (!headers.TryGetValue("Authorization", out var tokenHeader))
    return new StatusCodeResult(StatusCodes.Status403Forbidden);

var token = tokenHeader[0].Replace("Bearer ", "");

var publicKeyPem = Environment.GetEnvironmentVariable("Userfront_PublicKey");
var publicKey = RSA.Create();
publicKey.ImportFromPem(publicKeyPem);

try
{
    var json = JwtBuilder.Create()
                         .WithAlgorithm(new RS256Algorithm(publicKey))
                         .MustVerifySignature()
                         .Decode(token); 
}
catch (TokenExpiredException)
...
catch (SignatureVerificationException)
...
like image 153
jsiwrk Avatar answered Nov 12 '22 19:11

jsiwrk