Filter chaineasy0-2 years

A controller checks `if (SecurityContextHolder.getContext().getAuthentication() != null)` to decide whether the caller is logged in, and it is always true — even with no credentials. Separately, the same endpoint returns 401 to one caller and 403 to another. Which filters explain both observations?

AnonymousAuthenticationFilter sits late in the chain, after every filter that could authenticate the request. If none of them did, it installs an anonymous Authentication instead of leaving the context empty, so getAuthentication() is never null by the time your code runs, and a null check tells you nothing. The status codes come from ExceptionTranslationFilter, which sits just before the filter that makes the authorization decision and catches what that filter throws: if the caller is anonymous, the answer is 401 with a challenge (WWW-Authenticate), meaning 'I do not know who you are, sign in'; if the caller is authenticated and not allowed, the answer is 403, meaning 'I know who you are, and no'.

The lesson behind it →
More on Filter chain