Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A Spring Boot API returns 403 for requests with an expired JWT, and clients cannot tell they must refresh the token. What happened and how do you fix it?

A 403 for an expired token usually means the token failure never reached the standard 401 path: a custom filter caught the expiry exception and let the request continue as anonymous, and the chain had no proper entry point, so it fell back to a 403; or CSRF protection rejected the request with 403 before the token mattered; or the error dispatch to /error was itself secured and changed the response. With the standard resource server, an expired token produces 401 from BearerTokenAuthenticationEntryPoint with WWW-Authenticate: Bearer error="invalid_token". We find the culprit with TRACE logging for org.springframework.security and fix the configuration.

Why this question is asked

Clients rely on the difference between 401 and 403. A 401 with a bearer challenge tells a client to refresh the token and retry; a 403 tells it the user lacks permission, so most clients show an error and give up. When expired tokens produce 403, users get logged out or stuck with a 'forbidden' message whenever their token ages, which looks like a random bug. Interviewers ask this debugging question because the causes sit in different parts of the filter chain. In this answer, we will see what should happen, walk through the three common causes, find the real one with logging, and fix each.

1What Should Happen With an Expired Token

With Spring Security's resource server support, oauth2ResourceServer().jwt(), the BearerTokenAuthenticationFilter reads the Authorization: Bearer header and hands the token to JwtAuthenticationProvider. The JWT decoder checks the signature, and then validators check the claims; the timestamp validator rejects a token whose exp is in the past, allowing 60 seconds of clock skew by default.

That rejection becomes an InvalidBearerTokenException. The bearer filter catches it and calls its failure handler, which uses BearerTokenAuthenticationEntryPoint. The client receives exactly what it needs to refresh.

YAML
GET /api/orders
Authorization: Bearer eyJhbGciOi... (exp passed 5 minutes ago)
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Jwt expired at 2026-11-06T09:55:00Z", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
# the description wording varies by version

So if our API answers 403, something in our configuration or our own code has changed this path. There are three usual suspects.

2Cause 1: A Custom Filter Swallows the Failure

Many applications predate the resource server support and have a hand-written JWT filter. A typical one parses the token in a try block, logs any exception, and calls chain.doFilter() anyway.

Java
try {
Claims claims = parser.parseSignedClaims(token).getPayload(); // throws ExpiredJwtException
SecurityContextHolder.getContext().setAuthentication(toAuthentication(claims));
} catch (JwtException e) {
log.debug("invalid token", e); // swallowed
}
chain.doFilter(request, response); // continues as anonymous
Step throughHow an expired token turns into 403
ClientCustom JWT filterAuthorizationFilterExceptionTranslationFilter
Bearer token, exp in the past
ExpiredJwtException caught and logged
continue as anonymous
AccessDeniedException
anonymous, so call the entry point
Http403ForbiddenEntryPoint: 403

6 messages in order. Play them, or step through them one at a time.

Two small mistakes together produce the wrong status.

Now the request continues as anonymous. AuthorizationFilter denies it, and ExceptionTranslationFilter, seeing an anonymous user, calls the chain's AuthenticationEntryPoint. Here is the twist: a chain that configures no login method at all, no httpBasic(), formLogin() or oauth2ResourceServer(), has no entry point registered, and Spring Security falls back to Http403ForbiddenEntryPoint. So 'anonymous, please authenticate' comes out as 403. Both mistakes together, swallowing the error and having no entry point, produce exactly the symptom.

3Cause 2: CSRF Rejects the Request

CSRF protection guards against a malicious site making a logged-in browser send a request with its cookies. It is enabled by default and requires a CSRF token on every state-changing request (POST, PUT, PATCH, DELETE). A missing or wrong token is answered by the AccessDeniedHandler, so with 403.

In a stateless API that uses bearer tokens and no cookies, CSRF protection is unnecessary, and if it is left on, every POST without a CSRF token fails with 403, regardless of the JWT. The clue is that GET requests behave correctly and only writes fail. It may look like an expiry problem because developers test writes with old tokens.

4Cause 3: The Error Dispatch Is Secured

When something calls response.sendError(), the servlet container makes a second, internal request to the error page, /error in Spring Boot, with the dispatcher type ERROR. Since Spring Security 6, authorization applies to all dispatcher types, so that internal request is checked too. If /error is not permitted, the error dispatch itself is denied, and the response the client sees can have a different status or lose its body. Permitting /error, or all ERROR dispatches, makes the original status come through unchanged.

5Finding the Real Cause With TRACE Logging

Rather than guessing, we turn on TRACE logging for Spring Security and send one request with an expired token. The log lists each filter as it runs and says which one made the decision.

Properties
# application.properties
logging.level.org.springframework.security=TRACE
# Typical lines (exact wording varies by version):
# Securing POST /api/orders
# Invoking CsrfFilter (5/14)
# Invalid CSRF token found for http://localhost:8080/api/orders <- cause 2
# ...
# Invoking JwtAuthFilter (7/14) <- our own filter, no failure logged
# Set SecurityContextHolder to anonymous SecurityContext
# Sending AnonymousAuthenticationToken [...] to authentication entry point since access is denied <- cause 1
# ...
# Securing GET /error <- cause 3, if denied here

Notice that the log answers three questions at once: which filters are in the chain and in what order, whether the request was anonymous when it reached authorization, and which component produced the final status.

6The Fixes

For cause 1, the real fix is to delete the custom filter and use the standard resource server, which handles expiry, signature, issuer and audience, and returns the correct 401. If the filter must stay for now, it must call an AuthenticationEntryPoint that returns 401 on failure instead of continuing, and the chain must have an explicit entry point.

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**")
.authorizeHttpRequests(a -> a
.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll() // cause 3
.anyRequest().authenticated())
.csrf(c -> c.disable()) // cause 2: stateless, no cookies
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); // cause 1: standard 401 path
return http.build();
}
// expired token -> 401 WWW-Authenticate: Bearer error="invalid_token", ...
// valid token, missing scope -> 403 WWW-Authenticate: Bearer error="insufficient_scope", ...

Notice that disabling CSRF is only correct because the API is stateless and authenticated by a header. If the same chain also accepted session cookies from a browser, CSRF must stay on for those requests. After the fix, we add a test that sends an expired token and asserts 401 with the WWW-Authenticate header, so the behaviour cannot silently regress.

7Follow-up questions

Why does Spring Security default to 403 when no entry point is configured?

Without a login method, Spring Security does not know how a client should authenticate, so it cannot write a meaningful challenge. Http403ForbiddenEntryPoint is a safe refusal for pre-authenticated setups where authentication happens outside the application. For an API, we should always configure an entry point that sends 401.

Could clock skew make valid tokens look expired?

Yes. If the service's clock runs ahead of the identity provider's, tokens look expired early. The default validator allows 60 seconds of skew; we should run NTP on all hosts rather than raising the allowance, and the TRACE log or the error description shows the exp time to compare.

Why not just return 401 for every 403 to be safe?

Because clients would then try to refresh tokens for users who are simply not allowed, looping on refreshes and hiding real permission problems. The distinction is useful: 401 means fix your credentials, 403 means ask for access.

8Conclusion

In this answer, we saw that an expired token should produce 401 with a WWW-Authenticate: Bearer error="invalid_token" header from the standard resource server. A 403 means the failure took another path: a custom filter swallowed the expiry and the chain fell back to Http403ForbiddenEntryPoint, CSRF rejected a stateless write, or a secured error dispatch changed the response. TRACE logging for Spring Security shows which filter decided, and the fixes are the standard resource server with an explicit entry point, CSRF off for stateless APIs, and /error permitted.

What to say in the interviewAbout 90 seconds aloud

Open with

An expired token should give 401 with WWW-Authenticate: Bearer error invalid_token, because that's what tells the client to refresh. With the standard resource server that's what happens: the timestamp validator rejects the exp, the bearer filter's failure handler calls BearerTokenAuthenticationEntryPoint.

Then, if they want more

So a 403 means the failure took another path, and I'd check three suspects. First, a hand-written JWT filter that catches the expiry exception, logs it, and continues the chain. The request is now anonymous, authorization denies it, and ExceptionTranslationFilter calls the entry point.

If the chain has no login method configured, the default entry point is Http403ForbiddenEntryPoint, so anonymous becomes 403. Second, CSRF: if it's still enabled on a stateless API, every POST without a CSRF token gets 403 from CsrfFilter, whatever the JWT says; the clue is that GETs work.

Third, since Spring Security 6 the error dispatch to /error is also authorized, so if /error isn't permitted the error response can change. To find which one, I'd set logging.level.org.springframework.security to TRACE and send one request with an expired token; the log shows each filter, whether the request was anonymous at authorization, and who sent the response.

The fixes: replace the custom filter with oauth2ResourceServer jwt, or at least make it fail with a 401 entry point; disable CSRF for the stateless, header-authenticated API; and permit the ERROR dispatcher type. Then I'd add a test that an expired token returns 401 with the header.

About this answer

Last updated
12 November 2026
Versions it names
Spring Security 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Boot API returns 403 for requests with an expired JWT, and clients cannot tell...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/60ed06db31/