An unauthenticated request should enter authentication; an authenticated principal without permission should be denied access.
Spring Security 401 versus 403: authentication and access are separate failures
Classify the rejected request
A missing or invalid bearer token means the API cannot establish identity. The authentication entry point sends a 401 challenge. A valid token for an operator lacking the stock-adjust scope reaches authorization and should receive 403. ExceptionTranslationFilter routes these cases differently; a controller catch-all that maps both to 403 hides the real contract. Filter order matters before controller code runs.
Avoid leaking details
The response can identify the needed authentication scheme and a stable error code without echoing secrets or claims. Logs should record a request ID and the decision category, with care around token material. A browser login chain may redirect instead of returning JSON, so write route-specific tests for the actual chain selected by request matchers.
Exercise the matrix
Check no token, malformed token, valid token without authority, and valid token with authority. Assert status, challenge header where applicable, and that the protected service was not called on rejection. This page describes an HTTP contract; the exact handler configuration needs an application test.
Implementation sketch
mockMvc.perform(post("/api/stock/adjust"))
.andExpect(status().isUnauthorized());
mockMvc.perform(post("/api/stock/adjust")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_stock.read"))))
.andExpect(status().isForbidden());Cost and verification
The distinction adds no material runtime cost. It improves client recovery: obtain credentials after 401; request permission or change operation after 403.
Common Mistakes
- Do not return 403 for every missing-token request.
- Do not turn authorization failure into a login redirect for a bearer-token API.
- Do not expose token contents in an error body or application log.
Read next
Spring Security filter chain: authentication, CSRF and request order, Spring Security request matchers: order rules and cover the fallback, Spring resource server JWT: validate both issuer and intended audience, Test Spring JWT authorization through filters, service proxy and SQL.
