Sub topic 1
Authentication and authorization: what Spring Security does
Spring Security answers two questions for every request that reaches your API: who is calling, and are they allowed to do this? The first is authentication. The second is authorization. Nearly every setting you write in later chapters configures one of these two decisions, so it helps to separate them clearly now.
Prerequisites
This chapter assumes you can:
- Build a REST controller with Spring Boot and run the application.
- Read Java code that uses annotations and lambdas.
- Define a
@Beanin a@Configurationclass. - Recognize HTTP methods, status codes, and headers such as
Authorization. - Describe a password and a token as ways to prove identity.
You do not need to know Spring Security yet. This chapter explains its vocabulary and shows what it does with no configuration at all.
Two questions, asked in order
Authentication establishes identity. The caller presents credentials, such as a username and password or a signed token. Spring Security checks them and produces an object that represents the verified caller. If the check fails, the request is rejected.
Authorization decides permission. Once the caller's identity is known, Spring Security compares what the caller is allowed to do with what the request asks for. A valid user can still be refused.
The order matters. Authorization needs an identity to work with, so authentication always runs first. A request with no credentials is not given a special "nobody" answer. Spring Security treats it as an anonymous caller and then asks whether anonymous callers may access that path.
| Aspect | Authentication | Authorization |
|---|---|---|
| Question | Who are you? | May you do this? |
| Input | Credentials: password, token, certificate | The authenticated identity and the requested resource |
| Output | A verified `Authentication` object | Allow or deny |
| Failure status | 401 Unauthorized | 403 Forbidden |
| Typical setting | `httpBasic`, `oauth2ResourceServer`, `UserDetailsService` | `authorizeHttpRequests`, `@PreAuthorize` |
The status codes follow the two questions
The two failures use different HTTP status codes. Mixing them up is the most common source of confusion when debugging a secured API.
- 401 Unauthorized means authentication is missing or invalid. Despite its name, it describes a problem with identity. The response usually carries a
WWW-Authenticateheader that tells the client which scheme to use, for exampleBasicorBearer. - 403 Forbidden means the caller is known but not permitted. Sending the same credentials again will not help. The caller needs different permissions.
A useful rule is that 401 means "I don't know who you are" and 403 means "I know who you are, and the answer is no." There is one exception to remember. Spring Security also returns 403 when a state-changing request is missing a CSRF token. That is neither an identity problem nor a permission problem. A later chapter covers it.
The vocabulary
Spring Security models these decisions with a small set of types. You will meet them in code, logs, and stack traces.
| Term | What it is |
|---|---|
| `Authentication` | The object that represents a caller. Before checking, it holds the submitted credentials. After a successful check, it holds the verified identity and the caller's authorities. |
| Principal | The identity inside an `Authentication`. It is often a `UserDetails` object for password logins, or a `Jwt` object for token logins. |
| `GrantedAuthority` | One permission held by the caller, represented as a string such as `ROLE_ADMIN` or `SCOPE_orders.read`. |
| `SecurityContext` | A holder for the current caller's `Authentication`. |
| `SecurityContextHolder` | Gives code access to the `SecurityContext` of the current thread. |
Roles and authorities are the same thing
Spring Security stores only authorities. A role is an authority whose name starts with ROLE_. The two checks look different in configuration but compare against the same list:
hasRole("ADMIN")checks for the authorityROLE_ADMIN. It adds the prefix for you.hasAuthority("ROLE_ADMIN")checks the same thing, with the prefix written out.hasAuthority("SCOPE_orders.read")checks a scope authority.hasRole("SCOPE_orders.read")would look forROLE_SCOPE_orders.readand never match.
Use roles for coarse groups of users, such as USER and ADMIN. Use authorities for finer permissions, such as scopes that arrive in a token.
What you get with no configuration
Adding the Security starter is enough to change how your application behaves. In Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>With that dependency on the classpath, Spring Boot secures every endpoint. It creates one user named user and prints a random password in the startup log, on a line beginning Using generated security password. It accepts HTTP Basic credentials and also shows a login form to browsers. You can replace the generated user with fixed values for experiments:
spring.security.user.name=alice
spring.security.user.password=change-me
spring.security.user.roles=USERThese properties are for local experiments only. The password is stored in plain text in a file, and later chapters replace it with hashed passwords.
A controller that shows the result
This controller returns whatever Spring Security knows about the caller. It is a quick way to see authentication working.
import java.util.List;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WhoAmIController {
@GetMapping("/api/whoami")
Map<String, Object> whoAmI(Authentication authentication) {
List<String> authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.toList();
return Map.of(
"name", authentication.getName(),
"authorities", authorities);
}
}Spring MVC supplies the Authentication argument from the current SecurityContext. Start the application with the properties above and try three calls:
curl -i http://localhost:8080/api/whoamireturns401with aWWW-Authenticate: Basicheader. Authentication failed because no credentials were sent.curl -i -u alice:wrong http://localhost:8080/api/whoamialso returns401. The credentials were present but invalid.curl -u alice:change-me http://localhost:8080/api/whoamireturns200with{"name":"alice","authorities":["ROLE_USER"]}.
Nothing in the controller checks credentials. The checks happen before the controller runs, and the controller receives only requests that have already passed them.
Where each decision happens
The authentication and authorization decisions both happen inside the servlet filter layer, before Spring MVC dispatches the request to your controller. The next chapter covers that layer in detail. For now, the sequence below shows the order of the two decisions for one request.
Authorization can happen at more than one point. A rule on the URL path is checked before the controller. A rule placed on a method, such as @PreAuthorize, is checked when that method is called. A later chapter covers the second kind.
Common errors
- Expecting 403 for a missing login. An anonymous request to a protected path gets 401, not 403. If you see 403 for an anonymous caller, check whether the failure is a missing CSRF token on a POST, PUT, or DELETE.
- Putting
ROLE_insidehasRole. In current Spring Security versions,hasRole("ROLE_ADMIN")fails at startup with an error that says the role should not start withROLE_. WritehasRole("ADMIN"). - Testing with a browser. A browser sends
Accept: text/html, so Spring Security may redirect to the generated login form instead of returning 401. Usecurlor an HTTP client to see the real status code. - Treating authentication as proof of permission.
.authenticated()allows every verified user. If an endpoint is meant for admins only, you must say so with a role or authority rule. - Trusting the client to restrict access. Hiding a button in a front end does not protect an endpoint. Every rule has to be enforced on the server.
How the chapters build on this
The rest of the tutorial adds the pieces behind these two questions. The filter chain chapter shows where the checks run. The SecurityFilterChain chapter shows how you configure them. Chapters on passwords and JWT tokens cover the authentication side. Chapters on request rules and method security cover the authorization side. The testing chapter shows how to verify all of it, including the 401 and 403 split from this chapter.
Exercise
A client calls GET /api/admin/users with a valid username and password for a user who has only the USER role. The rule for that path is hasRole("ADMIN"). Which status code does Spring Security return, and which of the two decisions failed?
Show answer
It returns 403 Forbidden. Authentication succeeded, because the credentials were valid and the caller is known. Authorization failed, because the caller's authorities contain ROLEUSER but not ROLEADMIN.
Exercise
A teammate writes .requestMatchers("/api/reports/**").hasRole("ROLE_ANALYST") and the application will not start. What is wrong, and what is the correct rule? Which authority string does the correct rule check for?
Show answer
hasRole adds the ROLE prefix itself, so passing a value that already starts with ROLE is rejected at startup. The correct rule is hasRole("ANALYST"). It checks for the authority ROLEANALYST. Writing hasAuthority("ROLEANALYST") would be equivalent.