HTTP Status Codes for Auth Failures – Java Backend Interview
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
For a protected API, 401 Unauthorized is the authentication challenge. It means the request does not contain credentials that allow access to that resource—for example, a bearer token is missing, expired, or invalid. The response must include a WWW-Authenticate header so the client knows which authentication scheme applies.
403 Forbidden means the server understood the request but refuses it. In a Spring application, the common example is a signed-in user calling an admin endpoint without the required authority. Repeating the same credentials will not change that permission decision.
An API may return 404 instead of 403 for another user's private resource to avoid confirming that the resource exists. That is an application policy, not a replacement for correct access control, and it must be applied consistently.
HTTP Status Codes for Auth Failures – Java Backend Interview
Direct Answer
For a protected API, use 401 Unauthorized when the request lacks valid authentication credentials. A 401 response must include a WWW-Authenticate challenge. Use 403 Forbidden when the server understands the request but refuses it; the common Spring case is an authenticated principal that lacks permission. A server may return 404 instead when revealing that a protected resource exists would itself disclose information.
Code Example
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(a -> a
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.exceptionHandling(ex -> ex
// No/invalid credentials -> 401
.authenticationEntryPoint((req, res, e) ->
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required"))
// Authenticated but lacking role -> 403
.accessDeniedHandler((req, res, e) ->
res.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied")));
return http.build();
}
Spring already wires these defaults; you customize them to return JSON error bodies.
Common Mistakes & Pitfalls
- Returning 403 for every missing bearer token hides the authentication challenge; a protected bearer resource normally uses 401.
- Returning 401 for an authenticated permission failure can make clients retry credentials that cannot fix the policy.
- A 401 response without WWW-Authenticate omits the required challenge.
- Returning 200 with an error object breaks normal HTTP client behavior.
- Returning 404 to conceal existence works only when the API applies that policy consistently.
Check your understanding
Answer these without looking back at the article.
- Why is the 401 status name considered misleading?
- When might you return 404 instead of 403, and why?
- What header should accompany a 401 response?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.