一旦我们在前端获得 JWT 令牌,我们就可以使用 Authorization 标头或通过 cookie 来验证后端服务器中的无状态 RestAPI。 this video 中有很好的解释。
如果后端服务器在 C# .Net Framework (MVC) 中,如何验证接收到的 JWT? official documentation 指向未维护的 OWIN。
在看各种博客和文档时,理论说我们需要从 Keycloak Realms 的公共证书中获取 Modulus & Exponent 参数,然后使用 JWT.Net
进行验证如何实现?
答案 0 :(得分:1)
通过keycloak获取你所在领域的公共证书:
你会得到这样的东西,需要正确格式化:
复制您领域的 PublicCertificate
将其保存在 KeyCloakRealm.Public.crt
文件中
添加标题 -----BEGIN CERTIFICATE-----
将单行证书设为每行 64 字节
添加页脚 -----END CERTIFICATE-----
然后可以使用以下代码片段来验证收到的 JWT 令牌。 `` X509Certificate2 证书 = 新 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