Skip to content

Commit 51b75c1

Browse files
committed
Remap Nimbus JSON Parsing Errors
When Nimbus fails to parse either a JWK response or a JWT response, the error message contains information that either should or cannot be included in a Bearer Token response. For example, if the response from a JWK endpoint is invalid JSON, then Nimbus will send the entire response from the authentication server in the resulting exception message. This commit captures these exceptions and removes the parsing detail, replacing it with more generic information about the nature of the error. Fixes: spring-projectsgh-5517
1 parent 6516508 commit 51b75c1

File tree

2 files changed

+83
-11
lines changed

2 files changed

+83
-11
lines changed

oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupport.java

+26-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2017 the original author or authors.
2+
* Copyright 2002-2018 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -15,7 +15,15 @@
1515
*/
1616
package org.springframework.security.oauth2.jwt;
1717

18+
import java.net.MalformedURLException;
19+
import java.net.URL;
20+
import java.text.ParseException;
21+
import java.time.Instant;
22+
import java.util.LinkedHashMap;
23+
import java.util.Map;
24+
1825
import com.nimbusds.jose.JWSAlgorithm;
26+
import com.nimbusds.jose.RemoteKeySourceException;
1927
import com.nimbusds.jose.jwk.source.JWKSource;
2028
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
2129
import com.nimbusds.jose.proc.JWSKeySelector;
@@ -29,15 +37,10 @@
2937
import com.nimbusds.jwt.SignedJWT;
3038
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
3139
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
40+
3241
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
3342
import org.springframework.util.Assert;
3443

35-
import java.net.MalformedURLException;
36-
import java.net.URL;
37-
import java.time.Instant;
38-
import java.util.LinkedHashMap;
39-
import java.util.Map;
40-
4144
/**
4245
* An implementation of a {@link JwtDecoder} that "decodes" a
4346
* JSON Web Token (JWT) and additionally verifies it's digital signature if the JWT is a
@@ -48,6 +51,7 @@
4851
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK internally.
4952
*
5053
* @author Joe Grandja
54+
* @author Josh Cummings
5155
* @since 5.0
5256
* @see JwtDecoder
5357
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token (JWT)</a>
@@ -56,6 +60,9 @@
5660
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus JOSE + JWT SDK</a>
5761
*/
5862
public final class NimbusJwtDecoderJwkSupport implements JwtDecoder {
63+
private static final String DECODING_ERROR_MESSAGE_TEMPLATE =
64+
"An error occurred while attempting to decode the Jwt: %s";
65+
5966
private final URL jwkSetUrl;
6067
private final JWSAlgorithm jwsAlgorithm;
6168
private final ConfigurableJWTProcessor<SecurityContext> jwtProcessor;
@@ -108,7 +115,7 @@ private JWT parse(String token) {
108115
try {
109116
return JWTParser.parse(token);
110117
} catch (Exception ex) {
111-
throw new JwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
118+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
112119
}
113120
}
114121

@@ -135,8 +142,18 @@ private Jwt createJwt(String token, JWT parsedJwt) {
135142

136143
jwt = new Jwt(token, issuedAt, expiresAt, headers, jwtClaimsSet.getClaims());
137144

145+
} catch (RemoteKeySourceException ex) {
146+
if (ex.getCause() instanceof ParseException) {
147+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"));
148+
} else {
149+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
150+
}
138151
} catch (Exception ex) {
139-
throw new JwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
152+
if (ex.getCause() instanceof ParseException) {
153+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"));
154+
} else {
155+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
156+
}
140157
}
141158

142159
return jwt;

oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java

+57-2
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,14 @@
2222
import com.nimbusds.jwt.JWTParser;
2323
import com.nimbusds.jwt.SignedJWT;
2424
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
25+
import okhttp3.mockwebserver.MockResponse;
26+
import okhttp3.mockwebserver.MockWebServer;
2527
import org.junit.Test;
2628
import org.junit.runner.RunWith;
29+
import org.powermock.core.classloader.annotations.PowerMockIgnore;
2730
import org.powermock.core.classloader.annotations.PrepareForTest;
2831
import org.powermock.modules.junit4.PowerMockRunner;
32+
2933
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
3034

3135
import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode;
@@ -46,11 +50,17 @@
4650
*/
4751
@RunWith(PowerMockRunner.class)
4852
@PrepareForTest({NimbusJwtDecoderJwkSupport.class, JWTParser.class})
53+
@PowerMockIgnore("okhttp3.*")
4954
public class NimbusJwtDecoderJwkSupportTests {
5055
private static final String JWK_SET_URL = "https://provider.com/oauth2/keys";
5156
private static final String JWS_ALGORITHM = JwsAlgorithms.RS256;
5257

53-
private String unsignedToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJleHAiOi0yMDMzMjI0OTcsImp0aSI6IjEyMyIsInR5cCI6IkpXVCJ9.";
58+
private static final String JWK_SET = "{\"keys\":[{\"p\":\"49neceJFs8R6n7WamRGy45F5Tv0YM-R2ODK3eSBUSLOSH2tAqjEVKOkLE5fiNA3ygqq15NcKRadB2pTVf-Yb5ZIBuKzko8bzYIkIqYhSh_FAdEEr0vHF5fq_yWSvc6swsOJGqvBEtuqtJY027u-G2gAQasCQdhyejer68zsTn8M\",\"kty\":\"RSA\",\"q\":\"tWR-ysspjZ73B6p2vVRVyHwP3KQWL5KEQcdgc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J8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtdF4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAjjDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}";
59+
private static final String MALFORMED_JWK_SET = "malformed";
60+
61+
private static final String SIGNED_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJzY3AiOlsibWVzc2FnZTpyZWFkIl0sImV4cCI6NDY4Mzg5Nzc3Nn0.LtMVtIiRIwSyc3aX35Zl0JVwLTcQZAB3dyBOMHNaHCKUljwMrf20a_gT79LfhjDzE_fUVUmFiAO32W1vFnYpZSVaMDUgeIOIOpxfoe9shj_uYenAwIS-_UxqGVIJiJoXNZh_MK80ShNpvsQwamxWEEOAMBtpWNiVYNDMdfgho9n3o5_Z7Gjy8RLBo1tbDREbO9kTFwGIxm_EYpezmRCRq4w1DdS6UDW321hkwMxPnCMSWOvp-hRpmgY2yjzLgPJ6Aucmg9TJ8jloAP1DjJoF1gRR7NTAk8LOGkSjTzVYDYMbCF51YdpojhItSk80YzXiEsv1mTz4oMM49jXBmfXFMA";
62+
private static final String MALFORMED_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJuYmYiOnt9LCJleHAiOjQ2ODQyMjUwODd9.guoQvujdWvd3xw7FYQEn4D6-gzM_WqFvXdmvAUNSLbxG7fv2_LLCNujPdrBHJoYPbOwS1BGNxIKQWS1tylvqzmr1RohQ-RZ2iAM1HYQzboUlkoMkcd8ENM__ELqho8aNYBfqwkNdUOyBFoy7Syu_w2SoJADw2RTjnesKO6CVVa05bW118pDS4xWxqC4s7fnBjmZoTn4uQ-Kt9YSQZQk8YQxkJSiyanozzgyfgXULA6mPu1pTNU3FVFaK1i1av_xtH_zAPgb647ZeaNe4nahgqC5h8nhOlm8W2dndXbwAt29nd2ZWBsru_QwZz83XSKLhTPFz-mPBByZZDsyBbIHf9A";
63+
private static final String UNSIGNED_JWT = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJleHAiOi0yMDMzMjI0OTcsImp0aSI6IjEyMyIsInR5cCI6IkpXVCJ9.";
5464

5565
@Test
5666
public void constructorWhenJwkSetUrlIsNullThenThrowIllegalArgumentException() {
@@ -102,8 +112,53 @@ public void decodeWhenExpClaimNullThenDoesNotThrowException() throws Exception {
102112
public void decodeWhenPlainJwtThenExceptionDoesNotMentionClass() throws Exception {
103113
NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(JWK_SET_URL, JWS_ALGORITHM);
104114

105-
assertThatCode(() -> jwtDecoder.decode(this.unsignedToken))
115+
assertThatCode(() -> jwtDecoder.decode(UNSIGNED_JWT))
106116
.isInstanceOf(JwtException.class)
107117
.hasMessageContaining("Unsupported algorithm of none");
108118
}
119+
120+
@Test
121+
public void decodeWhenJwtIsMalformedThenReturnsStockException() throws Exception {
122+
try ( MockWebServer server = new MockWebServer() ) {
123+
server.enqueue(new MockResponse().setBody(JWK_SET));
124+
String jwkSetUrl = server.url("/.well-known/jwks.json").toString();
125+
126+
NimbusJwtDecoderJwkSupport decoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl);
127+
128+
assertThatCode(() -> decoder.decode(MALFORMED_JWT))
129+
.isInstanceOf(JwtException.class)
130+
.hasMessage("An error occurred while attempting to decode the Jwt: Malformed payload");
131+
}
132+
}
133+
134+
@Test
135+
public void decodeWhenJwkResponseIsMalformedThenReturnsStockException() throws Exception {
136+
try ( MockWebServer server = new MockWebServer() ) {
137+
server.enqueue(new MockResponse().setBody(MALFORMED_JWK_SET));
138+
String jwkSetUrl = server.url("/.well-known/jwks.json").toString();
139+
140+
NimbusJwtDecoderJwkSupport decoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl);
141+
142+
assertThatCode(() -> decoder.decode(SIGNED_JWT))
143+
.isInstanceOf(JwtException.class)
144+
.hasMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set");
145+
}
146+
}
147+
148+
@Test
149+
public void decodeWhenJwkEndpointIsUnresponsiveThenReturnsStockException() throws Exception {
150+
try ( MockWebServer server = new MockWebServer() ) {
151+
server.enqueue(new MockResponse().setBody(MALFORMED_JWK_SET));
152+
String jwkSetUrl = server.url("/.well-known/jwks.json").toString();
153+
154+
NimbusJwtDecoderJwkSupport decoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl);
155+
156+
server.shutdown();
157+
158+
assertThatCode(() -> decoder.decode(SIGNED_JWT))
159+
.isInstanceOf(JwtException.class)
160+
.hasMessage("An error occurred while attempting to decode the Jwt: " +
161+
"Couldn't retrieve remote JWK set: Connection refused (Connection refused)");
162+
}
163+
}
109164
}

0 commit comments

Comments
 (0)