简体   繁体   中英

How to validate the JWT token of keycloak in C# .Net?

Once we get the JWT token in the frontent, we can pass is using Authorization header or through cookies for authenticating our stateless RestAPIs in the backend server. Nicely explained in this video .

If the backend server is in C# .Net Framework (MVC), how can the received JWT be validated? The official documentation points towards OWIN , which is not maintained.

When seeing the various blogs and documentation, the theory says we need to get the Modulus & Exponent parameters from the Keycloak Realms' public certificate, and then verify it using JWT.Net

How can that be achieved?

Get the public certificate of your realm through keycloak:

获得公共证书

You will get something like this that needs to be formatted properly:

原始证书数据

  1. Copy the PublicCertificate of your realm

  2. Save it in a KeyCloakRealm.Public.crt file

  3. Add header -----BEGIN CERTIFICATE-----

  4. Make the single line certificate to be in 64bytes in each line

  5. Add footer -----END CERTIFICATE-----

crt文件格式

Then the following code snippet might be used to validate the received JWT token.

X509Certificate2 certificate = new 
X509Certificate2("KeyCloakRealm.Public.crt");

RSACryptoServiceProvider key =(RSACryptoServiceProvider)certificate.PublicKey.Key;
RSAParameters rsaParameters = key.ExportParameters(false);

RSA rsa = RSA.Create();
rsa.ImportParameters(rsaParameters);

var json = JwtBuilder.Create()
         .WithAlgorithm(new RS256Algorithm(rsa)) // asymmetric
         .MustVerifySignature()
         .Decode(token);
// The above method will throw an appropriate error if the JWT is invalid or cannot be validated against the supplied public keycloak realm
// If there is no exception, you will get the data in your json object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM