What is the difference between authentication and authorization in Spring Security?
Quick Answer
Authentication answers 'who is this request from?' — verifying an identity, typically via credentials (a username/password, a token) — and results in an Authentication object being populated in the SecurityContext. Authorization answers 'is this authenticated identity allowed to do this?' — checking the authenticated principal's granted authorities/roles against what a specific request or method requires, and is evaluated only after authentication has already succeeded.
Detailed Answer
These two terms are often used loosely together, but Spring Security (like security generally) treats them as distinct, sequential steps:
Authentication answers "who are you?" — verifying a claimed identity, typically by checking supplied credentials (a username/password pair, a bearer token, a client certificate) against some trusted source (a database, an identity provider). On success, Spring Security populates a SecurityContext (accessible via SecurityContextHolder.getContext()) with an Authentication object representing the now-verified principal and their granted authorities.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
auth.getName(); // "alice" — who they are
auth.getAuthorities(); // [ROLE_USER, ROLE_ADMIN] — what they're granted, established during authentication
Authorization answers "are you allowed to do this?" — given an already authenticated principal, checking whether their granted authorities/roles satisfy whatever a specific resource or action requires:
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN") // authorization rule
.requestMatchers("/api/**").authenticated() // just requires *some* valid identity
.anyRequest().permitAll());
@PreAuthorize("hasRole('ADMIN')") // method-level authorization
void deleteUser(Long id) { ... }
Sequencing matters: authorization checks only make sense after authentication has already established who the request is from — an unauthenticated request typically fails with 401 Unauthorized (authentication problem) before authorization is even evaluated, whereas an authenticated-but-insufficiently-privileged request fails with 403 Forbidden (authorization problem) once its identity is known but found lacking the required permission.
A useful mnemonic: authentication is about identity ("prove who you are"); authorization is about permission ("given who you are, what are you allowed to do").