1
0
Files
spring-auth-demo/src/main/java/com/ankurm/jwtauth/config/ApiExceptionHandler.java
asmhatre 4a8dab6739 Spring Security 7.1 JWT authentication on Spring Boot 4.1
Runnable companion for https://ankurm.com/spring-security-7-1-jwt-authentication-guide/

- login -> token issue -> OncePerRequestFilter -> SecurityContext, end to end
- HS256 and RS256 variants (RS256 publishes a real JWKS endpoint)
- the same API secured by the built-in oauth2ResourceServer().jwt(), for comparison
- 11 documentation chapters under docs/, interlinked with the code
- docs/output/ is real captured output, regenerated by scripts/run-all.sh
- 13 passing tests pinning the 401-vs-403 contract and the CSRF failure

Verified against Spring Boot 4.1.1, Spring Security 7.1.1, JDK 25.0.4.1.
2026-08-22 06:34:43 +00:00

42 lines
1.8 KiB
Java

package com.ankurm.jwtauth.config;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Login failures arrive here, not at the {@code AuthenticationEntryPoint} - the
* controller calls {@code AuthenticationManager} itself, so the exception is a plain
* MVC exception by the time anything security-shaped could see it.
*
* <p>Note every branch answers 401 with the same body. Telling a caller that the
* username exists but the password is wrong is a user-enumeration oracle.
*/
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler({BadCredentialsException.class, LockedException.class, DisabledException.class})
public ProblemDetail onAuthenticationFailure(AuthenticationException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.UNAUTHORIZED);
problem.setType(URI.create("https://ankurm.com/problems/invalid-credentials"));
problem.setTitle("Authentication failed");
problem.setDetail("Invalid username or password");
return problem;
}
@ExceptionHandler(AuthenticationException.class)
public ProblemDetail onAuthentication(AuthenticationException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.UNAUTHORIZED);
problem.setTitle("Authentication failed");
problem.setDetail("Invalid username or password");
return problem;
}
}