Sub topic 1
Authentication and authorization: what Spring Security does
Prerequisites
This chapter assumes you can build a REST controller with Spring Boot and read Java with lambdas and annotations. You should know how @Bean methods work in a @Configuration class. You should also know the basics of HTTP: methods, status codes, and headers such as Authorization. A rough idea of what a password and a token are is enough on the security side.
Two questions, asked in order
Spring Security answers two separate questions for every request that reaches your API.
- Authentication asks: who is making this request? The answer is an identity, such as the user
alice, backed by proof like a password or a signed token. - Authorization asks: is this identity allowed to do this? The answer is based on roles or authorities attached to the identity, and on the resource being requested.
Authentication comes first. You cannot decide what Alice may do until you know the caller is Alice. A request that carries no valid proof is anonymous, and most rules treat anonymous callers as having no permissions.
The two questions fail in different ways, and the HTTP status codes reflect that.
| Situation | Meaning | Status |
|---|---|---|
| No credentials, or invalid credentials | Authentication failed | 401 Unauthorized |
| Valid credentials, but not enough permission | Authorization failed | 403 Forbidden |
The name "401 Unauthorized" is misleading. It really means "unauthenticated". A 403 means the server knows who you are and has refused the request.
Roles and authorities
Spring Security represents what a user may do as a set of authorities. An authority is a string, such as orders.read. A role is an authority with the prefix ROLE_, so the role ADMIN is stored as the authority ROLE_ADMIN.
This matters when you write rules. hasRole("ADMIN") adds the ROLE_ prefix for you. hasAuthority("ROLE_ADMIN") is the same check written out in full. A common error is to write hasRole("ROLE_ADMIN"), which looks for ROLE_ROLE_ADMIN and never matches.
Where the two questions live in code
You rarely write the checks yourself. You describe your rules in one place, and Spring Security enforces them before your controller runs. The following rule set is the core of a typical API. It is shown as a preview, and later chapters explain each part.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class PreviewConfig {
@Bean
SecurityFilterChain preview(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}The httpBasic line is the authentication part. It tells Spring Security to read a username and password from the Authorization header. The authorizeHttpRequests block is the authorization part. It says which paths are open, which need the ADMIN role, and that everything else needs any authenticated user.
Rules are checked in order, and the first match wins. Put specific paths before general ones, and keep anyRequest() last.
The flow in one picture
The diagram shows both questions for a single request to a protected path.
What Spring Security does not do for you
Spring Security enforces the rules you give it. It does not decide your rules. If you forget to restrict a path, it follows the default you set. This is why the final anyRequest().authenticated() line is good practice: anything you did not think of is protected by default.
It also does not replace validation of input, safe database access, or secure deployment. It controls who gets in, not what a permitted caller sends.
Exercise
Exercise
A client sends a valid username and password for a user with only the USER role to an endpoint that requires ADMIN. Which status code does the API return, and which of the two questions failed?
Show answer
It returns 403 Forbidden. Authentication succeeded because the credentials were valid. Authorization failed because the user lacks the ADMIN role.
Exercise
Why does hasRole("ROLE_ADMIN") never match a user created with .roles("ADMIN")?
Show answer
hasRole adds the ROLE_ prefix itself, so it checks for ROLE_ROLE_ADMIN. The user's stored authority is ROLE_ADMIN. Use hasRole("ADMIN") or hasAuthority("ROLE_ADMIN").