Skip to content

Commit ca10187

Browse files
Kardeenjzheaux
authored andcommitted
Enhance JWT decoding error handling
Previously, the `decode` method threw a `JwtException` directly when encountering an unsupported algorithm or any exception during parsing. This commit introduces a more robust error handling mechanism. Now, instead of throwing exceptions directly, it returns a `Mono.error()` with a `BadJwtException` containing detailed error information. This approach provides more flexibility and allows the caller to handle errors in a more granular way, by being able to use project reactors onError functionality. Closes gh-14467
1 parent 56f4865 commit ca10187

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

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

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 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.
@@ -145,20 +145,17 @@ public void setClaimSetConverter(Converter<Map<String, Object>, Map<String, Obje
145145
}
146146

147147
@Override
148-
public Mono<Jwt> decode(String token) throws JwtException {
149-
JWT jwt = parse(token);
150-
if (jwt instanceof PlainJWT) {
151-
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
152-
}
153-
return this.decode(jwt);
154-
}
155-
156-
private JWT parse(String token) {
148+
public Mono<Jwt> decode(String token) {
157149
try {
158-
return JWTParser.parse(token);
150+
JWT jwt = JWTParser.parse(token);
151+
if (jwt instanceof PlainJWT) {
152+
return Mono.error(new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm()));
153+
}
154+
return this.decode(jwt);
159155
}
160156
catch (Exception ex) {
161-
throw new BadJwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
157+
return Mono.error(new BadJwtException(
158+
"An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex));
162159
}
163160
}
164161

0 commit comments

Comments
 (0)