Skip to content

Commit fbcf48c

Browse files
jzheauxrwinch
authored andcommitted
Low-level Nimbus Jwt Decoder
Introduces a JwtDecoder which takes a raw Nimbus JWTProcessor configuration. Fixes: gh-5648
1 parent db5e542 commit fbcf48c

File tree

3 files changed

+387
-78
lines changed

3 files changed

+387
-78
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
/*
2+
* Copyright 2002-2018 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.oauth2.jwt;
18+
19+
import java.text.ParseException;
20+
import java.time.Instant;
21+
import java.util.Collections;
22+
import java.util.LinkedHashMap;
23+
import java.util.Map;
24+
25+
import com.nimbusds.jose.RemoteKeySourceException;
26+
import com.nimbusds.jose.proc.SecurityContext;
27+
import com.nimbusds.jwt.JWT;
28+
import com.nimbusds.jwt.JWTClaimsSet;
29+
import com.nimbusds.jwt.JWTParser;
30+
import com.nimbusds.jwt.SignedJWT;
31+
import com.nimbusds.jwt.proc.JWTProcessor;
32+
33+
import org.springframework.core.convert.converter.Converter;
34+
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
35+
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
36+
import org.springframework.util.Assert;
37+
38+
/**
39+
* A low-level Nimbus implementation of {@link JwtDecoder} which takes a raw Nimbus configuration.
40+
*
41+
* @author Josh Cummings
42+
* @since 5.2
43+
*/
44+
public final class NimbusJwtDecoder implements JwtDecoder {
45+
private static final String DECODING_ERROR_MESSAGE_TEMPLATE =
46+
"An error occurred while attempting to decode the Jwt: %s";
47+
48+
private final JWTProcessor<SecurityContext> jwtProcessor;
49+
50+
private Converter<Map<String, Object>, Map<String, Object>> claimSetConverter =
51+
MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
52+
private OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefault();
53+
54+
/**
55+
* Configures a {@link NimbusJwtDecoder} with the given parameters
56+
*
57+
* @param jwtProcessor - the {@link JWTProcessor} to use
58+
*/
59+
public NimbusJwtDecoder(JWTProcessor<SecurityContext> jwtProcessor) {
60+
Assert.notNull(jwtProcessor, "jwtProcessor cannot be null");
61+
this.jwtProcessor = jwtProcessor;
62+
}
63+
64+
/**
65+
* Use this {@link Jwt} Validator
66+
*
67+
* @param jwtValidator - the Jwt Validator to use
68+
*/
69+
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) {
70+
Assert.notNull(jwtValidator, "jwtValidator cannot be null");
71+
this.jwtValidator = jwtValidator;
72+
}
73+
74+
/**
75+
* Use the following {@link Converter} for manipulating the JWT's claim set
76+
*
77+
* @param claimSetConverter the {@link Converter} to use
78+
*/
79+
public void setClaimSetConverter(Converter<Map<String, Object>, Map<String, Object>> claimSetConverter) {
80+
Assert.notNull(claimSetConverter, "claimSetConverter cannot be null");
81+
this.claimSetConverter = claimSetConverter;
82+
}
83+
84+
/**
85+
* Decode and validate the JWT from its compact claims representation format
86+
*
87+
* @param token the JWT value
88+
* @return a validated {@link Jwt}
89+
* @throws JwtException
90+
*/
91+
@Override
92+
public Jwt decode(String token) throws JwtException {
93+
JWT jwt = parse(token);
94+
if (jwt instanceof SignedJWT) {
95+
Jwt createdJwt = createJwt(token, jwt);
96+
return validateJwt(createdJwt);
97+
}
98+
throw new JwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
99+
}
100+
101+
private JWT parse(String token) {
102+
try {
103+
return JWTParser.parse(token);
104+
} catch (Exception ex) {
105+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
106+
}
107+
}
108+
109+
private Jwt createJwt(String token, JWT parsedJwt) {
110+
Jwt jwt;
111+
112+
try {
113+
// Verify the signature
114+
JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
115+
116+
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
117+
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
118+
119+
Instant expiresAt = (Instant) claims.get(JwtClaimNames.EXP);
120+
Instant issuedAt = (Instant) claims.get(JwtClaimNames.IAT);
121+
jwt = new Jwt(token, issuedAt, expiresAt, headers, claims);
122+
} catch (RemoteKeySourceException ex) {
123+
if (ex.getCause() instanceof ParseException) {
124+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"));
125+
} else {
126+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
127+
}
128+
} catch (Exception ex) {
129+
if (ex.getCause() instanceof ParseException) {
130+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"));
131+
} else {
132+
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
133+
}
134+
}
135+
136+
return jwt;
137+
}
138+
139+
private Jwt validateJwt(Jwt jwt){
140+
OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt);
141+
if (result.hasErrors()) {
142+
String description = result.getErrors().iterator().next().getDescription();
143+
throw new JwtValidationException(
144+
String.format(DECODING_ERROR_MESSAGE_TEMPLATE, description),
145+
result.getErrors());
146+
}
147+
148+
return jwt;
149+
}
150+
}

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

+13-78
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,17 @@
1818
import java.io.IOException;
1919
import java.net.MalformedURLException;
2020
import java.net.URL;
21-
import java.text.ParseException;
22-
import java.time.Instant;
2321
import java.util.Collections;
24-
import java.util.LinkedHashMap;
2522
import java.util.Map;
2623

2724
import com.nimbusds.jose.JWSAlgorithm;
28-
import com.nimbusds.jose.RemoteKeySourceException;
2925
import com.nimbusds.jose.jwk.source.JWKSource;
3026
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
3127
import com.nimbusds.jose.proc.JWSKeySelector;
3228
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
3329
import com.nimbusds.jose.proc.SecurityContext;
3430
import com.nimbusds.jose.util.Resource;
3531
import com.nimbusds.jose.util.ResourceRetriever;
36-
import com.nimbusds.jwt.JWT;
37-
import com.nimbusds.jwt.JWTClaimsSet;
38-
import com.nimbusds.jwt.JWTParser;
39-
import com.nimbusds.jwt.SignedJWT;
4032
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
4133
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
4234

@@ -47,7 +39,6 @@
4739
import org.springframework.http.RequestEntity;
4840
import org.springframework.http.ResponseEntity;
4941
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
50-
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
5142
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
5243
import org.springframework.util.Assert;
5344
import org.springframework.web.client.RestOperations;
@@ -62,27 +53,24 @@
6253
* <p>
6354
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK internally.
6455
*
56+
* @deprecated Use {@link NimbusJwtDecoder} instead
57+
*
6558
* @author Joe Grandja
6659
* @author Josh Cummings
6760
* @since 5.0
6861
* @see JwtDecoder
62+
* @see NimbusJwtDecoder
6963
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token (JWT)</a>
7064
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature (JWS)</a>
7165
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7517">JSON Web Key (JWK)</a>
7266
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus JOSE + JWT SDK</a>
7367
*/
68+
@Deprecated
7469
public final class NimbusJwtDecoderJwkSupport implements JwtDecoder {
75-
private static final String DECODING_ERROR_MESSAGE_TEMPLATE =
76-
"An error occurred while attempting to decode the Jwt: %s";
77-
7870
private final JWSAlgorithm jwsAlgorithm;
79-
private final ConfigurableJWTProcessor<SecurityContext> jwtProcessor;
8071
private final RestOperationsResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever();
8172

82-
private Converter<Map<String, Object>, Map<String, Object>> claimSetConverter =
83-
MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
84-
private OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefault();
85-
73+
private NimbusJwtDecoder delegate;
8674

8775
/**
8876
* Constructs a {@code NimbusJwtDecoderJwkSupport} using the provided parameters.
@@ -111,21 +99,18 @@ public NimbusJwtDecoderJwkSupport(String jwkSetUrl, String jwsAlgorithm) {
11199
this.jwsAlgorithm = JWSAlgorithm.parse(jwsAlgorithm);
112100
JWSKeySelector<SecurityContext> jwsKeySelector =
113101
new JWSVerificationKeySelector<>(this.jwsAlgorithm, jwkSource);
114-
this.jwtProcessor = new DefaultJWTProcessor<>();
115-
this.jwtProcessor.setJWSKeySelector(jwsKeySelector);
102+
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
103+
jwtProcessor.setJWSKeySelector(jwsKeySelector);
116104

117105
// Spring Security validates the claim set independent from Nimbus
118-
this.jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {});
106+
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {});
107+
108+
this.delegate = new NimbusJwtDecoder(jwtProcessor);
119109
}
120110

121111
@Override
122112
public Jwt decode(String token) throws JwtException {
123-
JWT jwt = this.parse(token);
124-
if (jwt instanceof SignedJWT) {
125-
Jwt createdJwt = this.createJwt(token, jwt);
126-
return this.validateJwt(createdJwt);
127-
}
128-
throw new JwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
113+
return this.delegate.decode(token);
129114
}
130115

131116
/**
@@ -135,7 +120,7 @@ public Jwt decode(String token) throws JwtException {
135120
*/
136121
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) {
137122
Assert.notNull(jwtValidator, "jwtValidator cannot be null");
138-
this.jwtValidator = jwtValidator;
123+
this.delegate.setJwtValidator(jwtValidator);
139124
}
140125

141126
/**
@@ -145,57 +130,7 @@ public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) {
145130
*/
146131
public final void setClaimSetConverter(Converter<Map<String, Object>, Map<String, Object>> claimSetConverter) {
147132
Assert.notNull(claimSetConverter, "claimSetConverter cannot be null");
148-
this.claimSetConverter = claimSetConverter;
149-
}
150-
151-
private JWT parse(String token) {
152-
try {
153-
return JWTParser.parse(token);
154-
} catch (Exception ex) {
155-
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
156-
}
157-
}
158-
159-
private Jwt createJwt(String token, JWT parsedJwt) {
160-
Jwt jwt;
161-
162-
try {
163-
// Verify the signature
164-
JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
165-
166-
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
167-
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
168-
169-
Instant expiresAt = (Instant) claims.get(JwtClaimNames.EXP);
170-
Instant issuedAt = (Instant) claims.get(JwtClaimNames.IAT);
171-
jwt = new Jwt(token, issuedAt, expiresAt, headers, claims);
172-
} catch (RemoteKeySourceException ex) {
173-
if (ex.getCause() instanceof ParseException) {
174-
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"));
175-
} else {
176-
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
177-
}
178-
} catch (Exception ex) {
179-
if (ex.getCause() instanceof ParseException) {
180-
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"));
181-
} else {
182-
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
183-
}
184-
}
185-
186-
return jwt;
187-
}
188-
189-
private Jwt validateJwt(Jwt jwt){
190-
OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt);
191-
if (result.hasErrors()) {
192-
String description = result.getErrors().iterator().next().getDescription();
193-
throw new JwtValidationException(
194-
String.format(DECODING_ERROR_MESSAGE_TEMPLATE, description),
195-
result.getErrors());
196-
}
197-
198-
return jwt;
133+
this.delegate.setClaimSetConverter(claimSetConverter);
199134
}
200135

201136
/**

0 commit comments

Comments
 (0)