Authentication vs authorization
Tell the two halves of security apart and know where Spring Security keeps the current user.
Open this lesson in the learning hubKey points
- Authentication answers "who are you". Authorization answers "may you do this".
- Authentication fails -> 401. Authorization fails -> 403. Clients rely on that difference, so do not blur it.
- Success produces an
Authenticationobject: a principal, optional credentials, and a list ofGrantedAuthority. - It is stored in
SecurityContextHolder, a ThreadLocal. Any code on the same request thread can read it. - In controllers, inject
Authenticationor@AuthenticationPrincipalinstead of reaching for the holder.
Example
@GetMapping("/api/me")
public Map<String, Object> me(Authentication auth) {
return Map.of(
"user", auth.getName(),
"authorities", auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.toList());
}
// Same request, deeper in the stack:
Authentication current = SecurityContextHolder.getContext().getAuthentication();
boolean anonymous = current == null || !current.isAuthenticated();
Identity first, permissions second — 401 means "log in", 403 means "not yours".
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.