From b2957f4411d35749fc15cc79c05b796300c3d206 Mon Sep 17 00:00:00 2001 From: "shengzhaoli.shengz" Date: Thu, 26 Oct 2023 21:55:06 +0800 Subject: [PATCH] JWT_BEARER flow/ jwk demo --- .../sos/service/JwtBearerFlowTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/test/java/com/monkeyk/sos/service/JwtBearerFlowTest.java b/src/test/java/com/monkeyk/sos/service/JwtBearerFlowTest.java index ccaa14c..7fc9adb 100644 --- a/src/test/java/com/monkeyk/sos/service/JwtBearerFlowTest.java +++ b/src/test/java/com/monkeyk/sos/service/JwtBearerFlowTest.java @@ -1,13 +1,18 @@ package com.monkeyk.sos.service; import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.ECDSASigner; import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jwt.JWTClaimsSet; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Date; +import static com.monkeyk.sos.web.controller.JwtBearerJwksController.ES256_KEY; +import static com.monkeyk.sos.web.controller.JwtBearerJwksController.RS256_KEY; import static org.junit.jupiter.api.Assertions.assertNotNull; /** @@ -66,10 +71,68 @@ public class JwtBearerFlowTest { * * @throws Exception e */ + @Test void rs256Assertion() throws Exception { + JWK rsJwk = JWK.parse(RS256_KEY); + + JWSSigner jwsSigner = new RSASSASigner(rsJwk.toRSAKey()); + JWSHeader header = new JWSHeader(JWSAlgorithm.RS256); + + String clientId = "dofOx6hjxlWw9qe2bnFvqbiPhuWwGWdn"; + JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() + .subject(clientId) + .issuer(clientId) + .audience("http://127.0.0.1:8080") + .expirationTime(Date.from(Instant.now().plusSeconds(300L))) + .build(); + + Payload payload = new Payload(claimsSet.toJSONObject()); + + JWSObject jwsObject = new JWSObject(header, payload); + //签名 + jwsObject.sign(jwsSigner); + + // 将 assertion 复制放到请求参数 client_assertion 的值 + String assertion = jwsObject.serialize(); + assertNotNull(assertion); +// System.out.println(assertion); + } + /** + * ES 生成 assertion + * SignatureAlgorithm: ES256 + * method: PRIVATE_KEY_JWT + * + * @throws Exception e + */ + @Test + void es256Assertion() throws Exception { + + JWK rsJwk = JWK.parse(ES256_KEY); + + JWSSigner jwsSigner = new ECDSASigner(rsJwk.toECKey()); + JWSHeader header = new JWSHeader(JWSAlgorithm.ES256); + + String clientId = "pRC9j1mwGNMuchoI8nwJ6blr1lmPBLha"; + JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() + .subject(clientId) + .issuer(clientId) + .audience("http://127.0.0.1:8080") + .expirationTime(Date.from(Instant.now().plusSeconds(300L))) + .build(); + + Payload payload = new Payload(claimsSet.toJSONObject()); + + JWSObject jwsObject = new JWSObject(header, payload); + //签名 + jwsObject.sign(jwsSigner); + + // 将 assertion 复制放到请求参数 client_assertion 的值 + String assertion = jwsObject.serialize(); + assertNotNull(assertion); +// System.out.println(assertion); }