diff --git a/core/src/main/java/org/springframework/security/core/AuthenticationException.java b/core/src/main/java/org/springframework/security/core/AuthenticationException.java index 9e1fb75608..914f165dca 100644 --- a/core/src/main/java/org/springframework/security/core/AuthenticationException.java +++ b/core/src/main/java/org/springframework/security/core/AuthenticationException.java @@ -18,6 +18,8 @@ package org.springframework.security.core; import java.io.Serial; +import org.springframework.util.Assert; + /** * Abstract superclass for all exceptions related to an {@link Authentication} object * being invalid for whatever reason. @@ -29,6 +31,16 @@ public abstract class AuthenticationException extends RuntimeException { @Serial private static final long serialVersionUID = 2018827803361503060L; + /** + * The {@link Authentication} object representing the failed authentication attempt. + *

+ * This field captures the authentication request that was attempted but ultimately + * failed, providing critical information for diagnosing the failure and facilitating + * debugging. If set, the value must not be null. + *

+ */ + private Authentication authRequest; + /** * Constructs an {@code AuthenticationException} with the specified message and root * cause. @@ -37,6 +49,7 @@ public abstract class AuthenticationException extends RuntimeException { */ public AuthenticationException(String msg, Throwable cause) { super(msg, cause); + this.authRequest = null; } /** @@ -46,6 +59,23 @@ public abstract class AuthenticationException extends RuntimeException { */ public AuthenticationException(String msg) { super(msg); + this.authRequest = null; + } + + + /** + * Sets the {@link Authentication} object representing the failed authentication + * attempt. + *

+ * This method allows the injection of the authentication request that resulted in a + * failure. The provided {@code authRequest} should not be null if set. + *

+ * @param authRequest the authentication request associated with the failed + * authentication attempt. + */ + public void setAuthRequest(Authentication authRequest) { + Assert.notNull(authRequest, "AuthRequest cannot be null"); + this.authRequest = authRequest; } }