From ca10187fd1d23550067f0c926d87f2eded05bec7 Mon Sep 17 00:00:00 2001 From: Hans Lindner Date: Thu, 18 Jan 2024 09:59:03 +0100 Subject: [PATCH] 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 --- .../oauth2/jwt/NimbusReactiveJwtDecoder.java | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoder.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoder.java index f5a98543fd..20fe295588 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoder.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2023 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -145,20 +145,17 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder { } @Override - public Mono decode(String token) throws JwtException { - JWT jwt = parse(token); - if (jwt instanceof PlainJWT) { - throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm()); - } - return this.decode(jwt); - } - - private JWT parse(String token) { + public Mono decode(String token) { try { - return JWTParser.parse(token); + JWT jwt = JWTParser.parse(token); + if (jwt instanceof PlainJWT) { + return Mono.error(new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm())); + } + return this.decode(jwt); } catch (Exception ex) { - throw new BadJwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex); + return Mono.error(new BadJwtException( + "An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex)); } }