'Signed JWT rejected' when spring resource server is restarted

207 views Asked by At

I am getting "Signed JWT rejected: Another algorithm expected, or no matching key(s) found" in spring resource server when I restart Spring resource server.

Error is coming from DefaultJwtProcessor

JWTClaimsSet claimsSet = extractJWTClaimsSet(signedJWT);

        List<? extends Key> keyCandidates = selectKeys(signedJWT.getHeader(), claimsSet, context);

        if (keyCandidates == null || keyCandidates.isEmpty()) {
            throw new BadJOSEException("Signed JWT rejected: Another algorithm expected, or no matching key(s) found");
        }

I followed the sample provided in spring authorization server.

How can I fix this issue?

Spring authorization server

@Bean
    @Lazy
    public JWKSource<SecurityContext> jwkSource() {
        final RSAKey rsaKey = generateRsa();
        final JWKSet jwkSet = new JWKSet(rsaKey);

        return new ImmutableJWKSet<>(jwkSet);
    }

public static RSAKey generateRsa() {
            final KeyPair keyPair = generateRsaKey();
            final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // @formatter:off
            return new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
            // @formatter:on
        }

static KeyPair generateRsaKey() {
        KeyPair keyPair;

        try {
            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }
Spring resource server

private JwtDecoder jwtDecoder(final String issuerUri) {
        return NimbusJwtDecoder.withIssuerLocation(issuerUri).jwsAlgorithm(SignatureAlgorithm.RS256).build();
    }

1

There are 1 answers

0
Steve Riesenberg On

The keys in the Getting Started example are generated at startup time. You can try loading keys from a persistent location, such as a file (example) or database (example).