@Bean JwtDecoder decoder() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(this.spec)); return new NimbusJwtDecoder(withPublicKey(publicKey).build()); } }
private PublicKeyJwtProcessorBuilder(RSAPublicKey key) { Assert.notNull(key, "key cannot be null"); this.jwsAlgorithm = JWSAlgorithm.parse(JwsAlgorithms.RS256); this.key = rsaKey(key); }
/** * Use the given public key to validate JWTs * * @param key the public key to use * @return a {@link PublicKeyJwtProcessorBuilder} for further configurations */ public static PublicKeyJwtProcessorBuilder withPublicKey(RSAPublicKey key) { return new PublicKeyJwtProcessorBuilder(key); }
@Test public void processWhenUsingPublicKeyThenSuccessfullyDecodes() throws Exception { JWTProcessor<SecurityContext> processor = JwtProcessors.withPublicKey(key()).build(); assertThat(processor.process(RS256_SIGNED_JWT, null)) .extracting(JWTClaimsSet::getSubject) .isEqualTo("test-subject"); }
@Test public void processWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception { JWTProcessor<SecurityContext> processor = JwtProcessors .withPublicKey(key()).jwsAlgorithm(JwsAlgorithms.RS512).build(); assertThatCode(() -> processor.process(RS256_SIGNED_JWT, null)) .isInstanceOf(BadJOSEException.class); }
@Test public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() { assertThatCode(() -> JwtProcessors.withPublicKey(key()) .jwsAlgorithm(JwsAlgorithms.ES256) .build()) .isInstanceOf(IllegalStateException.class); }
@Test public void processWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Exception { JWTProcessor<SecurityContext> processor = JwtProcessors .withPublicKey(key()).jwsAlgorithm(JwsAlgorithms.RS512).build(); assertThat(processor.process(RS512_SIGNED_JWT, null)) .extracting(JWTClaimsSet::getSubject) .isEqualTo("test-subject"); }