401 vs 403 and custom error responses
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every ShopLite error has the same JSON body, yet a guest who calls a protected URL gets a 401 with nothing in it. Spring Security's filters answer before any controller runs.
Where 401 and 403 come from: entry point and access-denied handler
An AuthenticationEntryPoint answers when Spring Security needs the caller to sign in: no token, or a token that fails its checks. It sends 401 Unauthorized.
With only oauth2ResourceServer(jwt), Spring Security writes the 401 and 403 answers itself. Here is what a guest and Asha receive when they try to change a price.
Example 1 · Spring Security's default 401 and 403
Runs in: the shoplite-api Spring Boot project
// SecurityConfig (part) with no entry point and no access-denied handler of our own: Spring's defaults.oauth2ResourceServer(oauth -> oauth .jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromToken())))# a guest, and Asha (customer), try to change a pricecurl -i -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price": 1.00}'curl -i -X PATCH http://localhost:8080/api/v1/products/6 -H "Authorization: Bearer $ASHA" \ -H "Content-Type: application/json" -d '{"price": 1.00}'curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer not-a-real-token"HTTP/1.1 401 WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource" HTTP/1.1 403 WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1" HTTP/1.1 401 WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Malformed token", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
What this code does
- Without our own classes, the guest gets 401 and Asha 403 with only a
WWW-Authenticateheader and an empty body, unlike every other ShopLite error. - The default 401 advertises a metadata URL ShopLite does not have, and for a bad token it repeats the decoder's own reason (
Malformed token). - The
@RestControllerAdvicewas in the app the whole time; it never saw these requests.
An AccessDeniedHandler answers when the caller is known but a rule says no: 403 Forbidden. ExceptionTranslationFilter makes the choice. An anonymous caller goes to the entry point, a signed-in one to the handler. A bad token never gets that far: BearerTokenAuthenticationFilter sends it straight to the entry point.
The defaults set the right status and a WWW-Authenticate header, but the body is empty, so a client that reads type from every ShopLite error gets nothing to read.
SecurityProblems. This lesson splits it into ProblemAuthenticationEntryPoint, ProblemAccessDeniedHandler and SecurityProblemWriter, so each job is easy to see; the CORS module merges them back into SecurityProblems.Why @RestControllerAdvice never sees these errors
@RestControllerAdvice marks a class whose @ExceptionHandler methods turn exceptions thrown while Spring MVC runs a controller into responses. Security filters run before Spring MVC, so it never sees their errors.
A request refused by a URL rule or a bad token never reaches a controller, so the advice is never asked. The picture follows one request through the filters.
So ShopLite's Problem Details handler did not help in the first example, where the 401 and 403 came back with empty bodies. Exceptions thrown inside a controller call are different. A @PreAuthorize denial passes through the advice first, which is why the previous lesson throws AccessDeniedException on from there.
So security errors need two small classes that live in the filter chain: an entry point and an access-denied handler that write the same Problem Details JSON as the rest of the API.
Problem Details for 401 and 403
Problem Details is the standard JSON shape for an API error: type, title, status, detail and instance, sent as application/problem+json. ShopLite uses it for every error, security errors included.
SecurityProblemWriter builds the 401 and 403 body once. The entry point and the handler both call it, and SecurityConfig registers them.
Example 2 · src/main/java/com/shoplite/common/security/SecurityProblemWriter.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.common.security;
import java.io.IOException;import java.util.LinkedHashMap;import java.util.Map;
import org.springframework.http.MediaType;import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import tools.jackson.databind.json.JsonMapper;
/** * Writes a Problem Details body from inside the security filters, where @RestControllerAdvice * cannot help: the request never reached a controller. Same fields, same order as every other error. */@Componentclass SecurityProblemWriter {
private static final String TYPE_BASE = "https://shoplite.example/problems/";
private final JsonMapper json;
SecurityProblemWriter(JsonMapper json) { this.json = json; }
void write(HttpServletRequest request, HttpServletResponse response, int status, String kind, String title, String detail) throws IOException { Map<String, Object> body = new LinkedHashMap<>(); body.put("type", TYPE_BASE + kind); body.put("title", title); body.put("status", status); body.put("detail", detail); body.put("instance", request.getRequestURI()); response.setStatus(status); response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE); response.getOutputStream().write(json.writeValueAsBytes(body)); }}$ curl -i -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price": 1.00}'
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/products/6"}
$ curl -i -X PATCH http://localhost:8080/api/v1/products/6 -H "Authorization: Bearer $ASHA" \
-H "Content-Type: application/json" -d '{"price": 1.00}'
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products/6"}
Server log:
WARN 25276 --- [shoplite-api] [io-8080-exec-4] c.s.c.s.ProblemAccessDeniedHandler : Access denied: PATCH /api/v1/products/6 for 2What this code does
- One method writes status, content type and the five fields in contract order, using the same
JsonMapper(Jackson 3,tools.jackson) as the controllers. - The guest now gets the
unauthorizedproblem with Spring'sWWW-Authenticate: Bearer ...header; Asha getsforbiddenwithinsufficient_scope. A client can branch ontypefor every ShopLite error. - The log line names the user id (
2is Asha's user id, the token'ssub), not the token.
Example 3 · ProblemAccessDeniedHandler and SecurityConfig
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/security/SecurityConfig.java (part)@BeanSecurityFilterChain securityFilterChain(HttpSecurity http, ProblemAuthenticationEntryPoint unauthorized, ProblemAccessDeniedHandler forbidden) throws Exception { http .authorizeHttpRequests(auth -> auth ...) .oauth2ResourceServer(oauth -> oauth .jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromToken())) .authenticationEntryPoint(unauthorized) .accessDeniedHandler(forbidden)) .exceptionHandling(ex -> ex .authenticationEntryPoint(unauthorized) .accessDeniedHandler(forbidden)) // signed in, but not allowed ... return http.build();}
package com.shoplite.common.security;
import java.io.IOException;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.security.access.AccessDeniedException;import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;import org.springframework.security.web.access.AccessDeniedHandler;import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;
/** 403 forbidden: a signed-in caller who is not allowed to do this. */@Componentclass ProblemAccessDeniedHandler implements AccessDeniedHandler {
private static final Logger log = LoggerFactory.getLogger(ProblemAccessDeniedHandler.class);
private final BearerTokenAccessDeniedHandler bearer = new BearerTokenAccessDeniedHandler(); private final SecurityProblemWriter writer;
ProblemAccessDeniedHandler(SecurityProblemWriter writer) { this.writer = writer; }
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException { log.warn("Access denied: {} {} for {}", request.getMethod(), request.getRequestURI(), request.getUserPrincipal() == null ? "anonymous" : request.getUserPrincipal().getName()); bearer.handle(request, response, ex); // 403 + WWW-Authenticate: Bearer error="insufficient_scope" writer.write(request, response, 403, "forbidden", "Forbidden", "You do not have permission to do this."); }}HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/me/orders"}What this code does
- The handler is a normal
@Component, so Spring injects it into theSecurityFilterChainbean method. - It is registered in both places:
exceptionHandlingcovers URL-rule denials,oauth2ResourceServercovers what the bearer filter handles itself. - The output is the admin calling
GET /api/v1/me/orders: the URL rule needsROLE_CUSTOMER, so the handler writes the 403 problem.
The writer uses the app's own Jackson JsonMapper, and a LinkedHashMap keeps the fields in contract order. Register both classes in SecurityConfig twice: in exceptionHandling(...) for requests without a token, and in oauth2ResourceServer(...) for requests with a bad token. Otherwise the Bearer defaults still answer some requests.
The handler also logs each denial with the method, path and user id (never the token). Repeated 403s from one account are exactly what someone probing for admin endpoints looks like.
WWW-Authenticate: Bearer and invalid tokens
The WWW-Authenticate header on a 401 tells the client how to authenticate. For bearer tokens (RFC 6750) it says Bearer when no token was sent, and error="invalid_token" when a token was sent and rejected.
ShopLite keeps Spring's standard header and adds only the body. Its entry point calls Spring's Bearer entry point first, then writes the Problem Details.
Example 4 · src/main/java/com/shoplite/common/security/ProblemAuthenticationEntryPoint.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.common.security;
import java.io.IOException;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.security.core.AuthenticationException;import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;
/** * 401 unauthorized: no token, or a token that is wrong, expired or edited. * Spring's own Bearer entry point sets the status and the RFC 6750 WWW-Authenticate header; * this class adds the same Problem Details body as every other error. */@Componentclass ProblemAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger log = LoggerFactory.getLogger(ProblemAuthenticationEntryPoint.class);
private final BearerTokenAuthenticationEntryPoint bearer = new BearerTokenAuthenticationEntryPoint(); private final SecurityProblemWriter writer;
ProblemAuthenticationEntryPoint(SecurityProblemWriter writer) { this.writer = writer; }
@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException { bearer.commence(request, response, ex); // 401 + WWW-Authenticate: Bearer ... if (ex instanceof InvalidBearerTokenException) { // A token was sent but failed the checks. The full reason goes to our log. log.info("Rejected access token on {} {}: {}", request.getMethod(), request.getRequestURI(), ex.getMessage()); writer.write(request, response, 401, "unauthorized", "Unauthorized", "The access token is invalid or has expired. Sign in again."); } else { writer.write(request, response, 401, "unauthorized", "Unauthorized", "Sign in to use this endpoint."); } }}# Asha's token with the last character of the signature changed
$ curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer ${ASHA%?}x"
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The access token is invalid or has expired. Sign in again.","instance":"/api/v1/me/orders"}
$ curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer not-a-real-token"
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Malformed token", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The access token is invalid or has expired. Sign in again.","instance":"/api/v1/me/orders"}
Server log (the reasons stay here):
INFO 25276 --- [shoplite-api] [io-8080-exec-1] c.s.c.s.ProblemAuthenticationEntryPoint : Rejected access token on GET /api/v1/me/orders: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature
INFO 25276 --- [shoplite-api] [io-8080-exec-7] c.s.c.s.ProblemAuthenticationEntryPoint : Rejected access token on GET /api/v1/me/orders: An error occurred while attempting to decode the Jwt: Malformed tokenWhat this code does
- Spring's
BearerTokenAuthenticationEntryPointsets the status and the RFC 6750 header:invalid_tokenplus the decoder's short reason.InvalidBearerTokenExceptionmeans a token was sent and rejected. - The body is the same fixed sentence for an edited signature and for plain rubbish; an expired token takes the same path.
- The full decoder message is logged for the team; the client gets the header's short reason and a clear next step: sign in again.
Clients use the header to decide between "show the login screen" and "refresh the token". A 403 for a bearer caller says error="insufficient_scope". Spring also adds resource_metadata, a /.well-known/oauth-protected-resource URL from RFC 9728 that OAuth clients may read (ShopLite does not serve it yet), and copies the decoder's short reason into error_description, such as Malformed token or Invalid signature.
The body uses one fixed sentence for every rejected token, whether it is edited, expired or rubbish. The full reason goes into the server log at INFO level, and neither the key nor the token's contents appear anywhere.
Not leaking details in security errors
An error message leak is an error that says more than the client needs: which e-mails have accounts, which check a token failed, or a stack trace. A security error should say what to do, never why in detail.
A login error must not tell an attacker which e-mails exist. This handler answers a wrong password and an unknown e-mail with the same words.
Example 5 · One message for both login failures
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/GlobalExceptionHandler.java (part)/** Wrong e-mail or wrong password at POST /auth/login: one answer for both, so accounts cannot be guessed. */@ExceptionHandler(BadCredentialsException.class)ProblemDetail handleBadCredentials(BadCredentialsException ex, HttpServletRequest request) { return problem(HttpStatus.UNAUTHORIZED, "unauthorized", "Unauthorized", "Email or password is wrong.", request.getRequestURI());}
@ExceptionHandler(Exception.class)ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) { log.error("Unexpected error on {} {}", request.getMethod(), request.getRequestURI(), ex); // full cause: log only return problem(HttpStatus.INTERNAL_SERVER_ERROR, "internal-error", "Internal server error", "Something went wrong on our side. Please try again later.", request.getRequestURI());}$ curl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \
-d '{"email":"asha.rao@example.com","password":"wrong-password-123"}'
HTTP/1.1 401
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Email or password is wrong.","instance":"/api/v1/auth/login"}
$ curl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \
-d '{"email":"nobody@example.com","password":"asha-dev-password"}'
HTTP/1.1 401
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Email or password is wrong.","instance":"/api/v1/auth/login"}What this code does
DaoAuthenticationProviderturns both an unknown e-mail and a wrong password intoBadCredentialsException, and the handler gives both the same 401 body.- This 401 has no
WWW-Authenticateheader: it is the answer of the login endpoint itself, not a request for a token. - The catch-all handler logs the full exception and sends only a generic sentence, so no stack trace or class name leaves the server.
One login message for both cases, "Email or password is wrong.", stops attackers from testing which e-mails have accounts. One invalid_token message hides which check a forged token failed. Unexpected errors keep the generic 500 detail; stack traces, exception class names, SQL and versions stay in the log.
What is safe to show: the status, the problem type, a short sentence and the path. The login error comes from inside a controller, so the global handler's @ExceptionHandler(BadCredentialsException.class) answers it, not the entry point.
Find the bug
Find the leak
Each snippet tells an attacker too much. Tap the line that leaks, then check the fix.
Login answers differently for an unknown e-mail.
Round 1 of 3Next step
Check your understanding
12 quick questions