Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The selectJwk method of NimbusJwtEncoder class should not throw Exception when jwks size great than one #16170 #16354

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,28 @@

package org.springframework.security.oauth2.jwt;

import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.*;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.produce.JWSSignerFactory;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
* An implementation of a {@link JwtEncoder} that encodes a JSON Web Token (JWT) using the
* JSON Web Signature (JWS) Compact Serialization format. The private/secret key used for
Expand All @@ -61,7 +48,6 @@
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK.
*
* @author Joe Grandja
* @since 5.6
* @see JwtEncoder
* @see com.nimbusds.jose.jwk.source.JWKSource
* @see com.nimbusds.jose.jwk.JWK
Expand All @@ -73,6 +59,7 @@
* Compact Serialization</a>
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus
* JOSE + JWT SDK</a>
* @since 5.6
*/
public final class NimbusJwtEncoder implements JwtEncoder {

Expand All @@ -84,6 +71,8 @@ public final class NimbusJwtEncoder implements JwtEncoder {

private final Map<JWK, JWSSigner> jwsSigners = new ConcurrentHashMap<>();

private Converter<List<JWK>, JWK> jwkSelector;

private final JWKSource<SecurityContext> jwkSource;

/**
Expand All @@ -95,6 +84,10 @@ public NimbusJwtEncoder(JWKSource<SecurityContext> jwkSource) {
this.jwkSource = jwkSource;
}

public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
this.jwkSelector = jwkSelector;
}

@Override
public Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException {
Assert.notNull(parameters, "parameters cannot be null");
Expand All @@ -118,21 +111,21 @@ private JWK selectJwk(JwsHeader headers) {
try {
JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers));
jwks = this.jwkSource.get(jwkSelector, null);
}
catch (Exception ex) {
} catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to select a JWK signing key -> " + ex.getMessage()), ex);
}

if (jwks.size() > 1) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Found multiple JWK signing keys for algorithm '" + headers.getAlgorithm().getName() + "'"));
}

if (jwks.isEmpty()) {
throw new JwtEncodingException(
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
}
if (null != this.jwkSelector) {
return this.jwkSelector.convert(jwks);
}
if (jwks.size() > 1) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Found multiple JWK signing keys for algorithm '" + headers.getAlgorithm().getName() + "'"));
}

return jwks.get(0);
}
Expand All @@ -146,8 +139,7 @@ private String serialize(JwsHeader headers, JwtClaimsSet claims, JWK jwk) {
SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
try {
signedJwt.sign(jwsSigner);
}
catch (JOSEException ex) {
} catch (JOSEException ex) {
throw new JwtEncodingException(
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
}
Expand All @@ -167,8 +159,7 @@ private static JWKMatcher createJwkMatcher(JwsHeader headers) {
.x509CertSHA256Thumbprint(Base64URL.from(headers.getX509SHA256Thumbprint()))
.build();
// @formatter:on
}
else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
} else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
// @formatter:off
return new JWKMatcher.Builder()
.keyType(KeyType.forAlgorithm(jwsAlgorithm))
Expand Down Expand Up @@ -206,8 +197,7 @@ private static JwsHeader addKeyIdentifierHeadersIfNecessary(JwsHeader headers, J
private static JWSSigner createSigner(JWK jwk) {
try {
return JWS_SIGNER_FACTORY.createJWSSigner(jwk);
}
catch (JOSEException ex) {
} catch (JOSEException ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to create a JWS Signer -> " + ex.getMessage()), ex);
}
Expand All @@ -224,8 +214,7 @@ private static JWSHeader convert(JwsHeader headers) {
if (!CollectionUtils.isEmpty(jwk)) {
try {
builder.jwk(JWK.parse(jwk));
}
catch (Exception ex) {
} catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
}
Expand Down Expand Up @@ -342,8 +331,7 @@ private static JWTClaimsSet convert(JwtClaimsSet claims) {
private static URI convertAsURI(String header, URL url) {
try {
return url.toURI();
}
catch (Exception ex) {
} catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Unable to convert '" + header + "' JOSE header to a URI"), ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,27 @@ public void encodeWhenJwkMultipleSelectedThenThrowJwtEncodingException() throws
.withMessageContaining("Found multiple JWK signing keys for algorithm 'RS256'");
}

@Test
public void encodeWhenJwkMultipleSelectedWithJwkSelector() throws Exception {
RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
this.jwkList.add(rsaJwk);
this.jwkList.add(rsaJwk);
this.jwtEncoder.setJwkSelector(jwkSelector -> jwkSelector.get(0));

JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();

Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.ALG, SignatureAlgorithm.RS256);

this.jwtEncoder.setJwkSelector(jwkSelector -> jwkSelector.get(jwkSelector.size()-1));
jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.ALG, SignatureAlgorithm.RS256);
this.jwtEncoder.setJwkSelector(null);
}


@Test
public void encodeWhenJwkSelectEmptyThenThrowJwtEncodingException() {
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
Expand Down