如何在 C# .Net 中验证 keycloak 的 JWT 令牌?
How to validate the JWT token of keycloak in C# .Net?
一旦我们在前端获得 JWT 令牌,我们就可以通过使用授权 header 或通过 cookie 在后端服务器中验证我们的无状态 RestAPI。在 this video.
中有很好的解释
如果后端服务器是C# .Net Framework (MVC),如何验证接收到的JWT? official documentation points towards OWIN,未维护。
当看到各种博客和文档时,理论说我们需要从 Keycloak Realms 的 public 证书中获取模数和指数参数,然后使用 JWT.Net[=13 进行验证=]
如何实现?
通过 keycloak 获取您领域的 public 证书:
您将得到需要正确格式化的类似内容:
复制您领域的 PublicCertificate
将其保存在 KeyCloakRealm.Public.crt
文件中
添加header-----BEGIN CERTIFICATE-----
使单行证书每行64字节
添加页脚-----END CERTIFICATE-----
然后可以使用以下代码片段来验证收到的 JWT 令牌。
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
一旦我们在前端获得 JWT 令牌,我们就可以通过使用授权 header 或通过 cookie 在后端服务器中验证我们的无状态 RestAPI。在 this video.
中有很好的解释如果后端服务器是C# .Net Framework (MVC),如何验证接收到的JWT? official documentation points towards OWIN,未维护。
当看到各种博客和文档时,理论说我们需要从 Keycloak Realms 的 public 证书中获取模数和指数参数,然后使用 JWT.Net[=13 进行验证=]
如何实现?
通过 keycloak 获取您领域的 public 证书:
您将得到需要正确格式化的类似内容:
复制您领域的 PublicCertificate
将其保存在
KeyCloakRealm.Public.crt
文件中添加header
-----BEGIN CERTIFICATE-----
使单行证书每行64字节
添加页脚
-----END CERTIFICATE-----
然后可以使用以下代码片段来验证收到的 JWT 令牌。
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