Authentication vs authorization, the filter chain, configuring access, and method-level security.
UserDetailsService, UserDetails,
GrantedAuthority); URL authorization with matchers; and enabling method security
(@PreAuthorize).
| Authentication (authn) | Authorization (authz) | |
|---|---|---|
| Question | Who are you? | What are you allowed to do? |
| Does | Verifies identity (username/password, token…) | Grants/denies access to a resource |
| Order | First | After authentication |
Spring Security plugs into a web app as a chain of servlet filters that intercept
every request before it reaches your controllers. A single FilterChainProxy (registered as
springSecurityFilterChain via a DelegatingFilterProxy) runs the individual security
filters — authentication, authorization, CSRF, and so on.
| Type | Role |
|---|---|
SecurityContextHolder | Holds the SecurityContext (→ the current Authentication) for the thread |
Authentication | The token for the current request: the principal + credentials + authorities |
UserDetailsService | Loads a user by username (loadUserByUsername) → returns UserDetails |
UserDetails | The user's stored info: username, password, authorities |
GrantedAuthority | A single permission / role held by the user |
PasswordEncoder | Hashes & verifies passwords (e.g. BCryptPasswordEncoder) |
In the Boot 2.5 / Security 5.5 era you extend WebSecurityConfigurerAdapter and configure
HttpSecurity. Restrict URLs with matchers and access rules:
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // URL-pattern authorization
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and().formLogin();
antMatchers(...), mvcMatchers(...), regexMatchers(...) — then rules like hasRole, hasAuthority, permitAll, authenticated.UserDetailsService + PasswordEncoder).Beyond URLs, you can secure individual methods (typically service-layer). Turn it on with
@EnableGlobalMethodSecurity, choosing which annotation styles to enable:
| Annotation | Style | Enabled by |
|---|---|---|
@PreAuthorize / @PostAuthorize | SpEL expressions (e.g. hasRole('ADMIN')) | prePostEnabled = true |
@Secured | Role names only, no SpEL | securedEnabled = true |
@RolesAllowed | JSR-250 | jsr250Enabled = true |
@EnableGlobalMethodSecurity(prePostEnabled = true) // enables @PreAuthorize/@PostAuthorize
public class MethodSecurityConfig { }
@PreAuthorize("hasRole('ADMIN')")
public void deleteAccount(Long id) { ... }
Read "Architecture" (filter chain), "Authentication" (UserDetailsService), "Authorization", and "Method Security".
The authn/authz distinction, the core types, and enabling method security are the money questions. Options shuffle on every load.
@PreAuthorize example, or the difference
between hasRole and hasAuthority? Ask. Say "continue" to start
Section 6 — Spring Boot with Lesson 15.