Spring Security
Mid-level Always asked 7 min
On this page
The question
What is the difference between authentication and authorization, and how does Spring Security apply them?
30-second answer
Authentication proves who you are, and authorization decides what you may do. Spring Security runs both in servlet filters, before any controller. A filter turns credentials into an Authentication in the SecurityContext, then AuthorizationFilter checks the rule for the URL. Missing or bad credentials give 401, and a known caller without permission gets 403.
Understand it
A request through the security filter chain
Step by stepSpring Security is a set of servlet filters, so it runs before DispatcherServlet. FilterChainProxy picks the first SecurityFilterChain that matches the URL.
View as text
Seven stations in a column: FilterChainProxy, the security context filter, the bearer token filter, the anonymous filter, the exception translation filter, the authorization filter, and finally DispatcherServlet. A marker shows where the request is, and a mark gives the result.
Spring Security is a set of servlet filters, so it runs before DispatcherServlet. FilterChainProxy picks the first SecurityFilterChain that matches the URL.
SecurityContextHolderFilter prepares an empty SecurityContext for this thread. In a stateless API, nothing is loaded from a session.
BearerTokenAuthenticationFilter reads the Authorization header. It checks the signature, expiry and issuer of the JWT.
A tampered or expired token stops here with 401 and a WWW-Authenticate header. Neither the controller nor its advice ever runs.
A good token becomes an Authentication in the SecurityContext. Scopes become authorities with a prefix: scope read is SCOPE_read.
AuthorizationFilter, near the end, compares the rule for this URL with those authorities. With no token, an anonymous user reaches this point.
No token at all: the anonymous user fails the rule, ExceptionTranslationFilter catches the denial and asks for authentication, and the client gets 401.
A valid token without the needed authority: ExceptionTranslationFilter turns the denial into 403. The caller is known, and the answer is no.
All filters passed, so the request continues to DispatcherServlet and your controller, which can read the user from the SecurityContext.
Seven stations in a column: FilterChainProxy, the security context filter, the bearer token filter, the anonymous filter, the exception translation filter, the authorization filter, and finally DispatcherServlet. A marker shows where the request is, and a mark gives the result.
Spring Security is a set of servlet filters, so it runs before DispatcherServlet. FilterChainProxy picks the first SecurityFilterChain that matches the URL.
SecurityContextHolderFilter prepares an empty SecurityContext for this thread. In a stateless API, nothing is loaded from a session.
BearerTokenAuthenticationFilter reads the Authorization header. It checks the signature, expiry and issuer of the JWT.
A tampered or expired token stops here with 401 and a WWW-Authenticate header. Neither the controller nor its advice ever runs.
A good token becomes an Authentication in the SecurityContext. Scopes become authorities with a prefix: scope read is SCOPE_read.
AuthorizationFilter, near the end, compares the rule for this URL with those authorities. With no token, an anonymous user reaches this point.
No token at all: the anonymous user fails the rule, ExceptionTranslationFilter catches the denial and asks for authentication, and the client gets 401.
A valid token without the needed authority: ExceptionTranslationFilter turns the denial into 403. The caller is known, and the answer is no.
All filters passed, so the request continues to DispatcherServlet and your controller, which can read the user from the SecurityContext.
Takeaway: Filters authenticate first and authorize near the end. Missing or bad credentials give 401, a known caller without permission gets 403, and both happen before any controller.
The parts of a JWT
Tap the partsSelect a part to see what it does.
Tap a part of the token. Rows show the claims of a decoded token, and the colored bar shows the three parts it is made of.
View as text
A bar with the three dot-separated parts of a token: header, payload and signature. Below it, six rows show the alg claim, the sub, scope, exp and iss claims, and the signature.
alg, in the header: "alg": "RS256". The header names the signing algorithm.
sub, in the payload: "sub": "ana". The subject: who the token is about.
scope, in the payload: "scope": "read". What the token may do.
exp, in the payload: "exp": 1794018271. The expiry, in seconds since 1970.
iss, in the payload: "iss": "https://auth...". Who issued the token.
signature, in the signature: over header.payload. A signature over the header and the payload.
A bar with the three dot-separated parts of a token: header, payload and signature. Below it, six rows show the alg claim, the sub, scope, exp and iss claims, and the signature.
alg, in the header: "alg": "RS256". The header names the signing algorithm.
sub, in the payload: "sub": "ana". The subject: who the token is about.
scope, in the payload: "scope": "read". What the token may do.
exp, in the payload: "exp": 1794018271. The expiry, in seconds since 1970.
iss, in the payload: "iss": "https://auth...". Who issued the token.
signature, in the signature: over header.payload. A signature over the header and the payload.
Takeaway: A JWT is three Base64URL parts joined by dots. The payload is readable by anyone. Only the signature stops tampering, which lets the server check it with no session.
In code
@Configuration
@EnableMethodSecurity
class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // no cookies, so no CSRF risk
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth -> oauth.jwt(jwt -> {}))
.build();
}
}@RestController
class ReportController {
@PreAuthorize("hasAuthority('SCOPE_admin')")
@GetMapping("/reports")
String report(Authentication user) {
return "for " + user.getName();
}
}
@RestControllerAdvice
class ApiErrors {
// Also catches the access denied exception, so 403 becomes 500
@ExceptionHandler(Exception.class)
ResponseEntity<String> any(Exception e) {
return ResponseEntity.internalServerError().body("Sorry");
}
}@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // bcrypt by default: "{bcrypt}$2a$10$..."
}
String hash = passwordEncoder.encode("s3cret");
boolean ok = passwordEncoder.matches("s3cret", hash); // true: the salt is stored inside the hashSolve it
A user reads someone else’s order by changing the id in the URL
GET /orders/{id} requires a valid JWT with role USER. A tester logged in as Ana changes the id from 41 to 42 and gets
Ben’s order, with his address. Explain the hole and close it.
- Name it. Authentication works: the server knows this is Ana. Authorization only checks the role, not whether this order belongs to her. This is broken object-level authorization.
- State the rule. An order may be read by its owner or by an admin. The rule depends on the data, so a URL pattern alone cannot enforce it.
- Enforce it where the data is loaded. Query by id and owner, so another user’s order is simply not found.
- Choose the status. Answer 404, not 403, so the response does not confirm that order 42 exists.
- Check. Tests: Ana reading 41 gets 200, Ana reading 42 gets 404, an admin reading 42 gets 200.
interface OrderRepository extends JpaRepository<Order, Long> {
Optional<Order> findByIdAndOwner(long id, String owner);
}
@GetMapping("/orders/{id}")
OrderDto get(@PathVariable long id, Authentication auth) { // auth.getName() is the token's subject
boolean admin = auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
Optional<Order> order = admin ? orders.findById(id) : orders.findByIdAndOwner(id, auth.getName());
return order.map(OrderDto::from).orElseThrow(() -> new OrderNotFoundException(id)); // 404 either way
}How to answer
- Authentication always comes first; authorization needs to know who is asking.
SecurityContextHolderholds the current user for the thread.- Method rules such as
@PreAuthorizeadd a second check on individual methods. - An authority is a plain string, such as
SCOPE_readorROLE_ADMIN.
Common mistakes
- Mixing up 401 and 403.
- Writing security checks inside controllers instead of using the filter chain or method rules.
Follow-up questions
What is the security filter chain, and how does a request go through it?
DelegatingFilterProxy connects the servlet container to the FilterChainProxy bean, which picks the first SecurityFilterChain matching the request and runs its filters in a fixed order. Authentication filters such as BearerTokenAuthenticationFilter come first, and ExceptionTranslationFilter and AuthorizationFilter come last. You declare chains as beans.
- All of this runs before
DispatcherServlet. ExceptionTranslationFilterturns security exceptions into 401 or 403.- Several chains with
securityMatchercan serve an API and a web UI. - Set the
logging.level.org.springframework.securitytoTRACEto see each filter run.
See it in the infographic: A request through the security filter chain
What is a JWT, and what are its pros and cons?
A signed token with three Base64URL parts: a header, a payload of claims, and a signature. Any service holding the public key can verify it with no database call, which suits microservices. The cost: it is readable by anyone, and hard to revoke before it expires. So keep it short-lived, put no secrets in it, and use refresh tokens.
- Signed is not encrypted; Base64URL is only an encoding.
- Prefer an asymmetric algorithm, so services cannot mint tokens.
- Reject
alg: none, as Spring's decoder does. - Revoking one needs a deny list or short lifetimes.
What does it mean for a Spring Boot API to be an OAuth2 resource server?
The API does not log anyone in. It accepts access tokens issued by an authorization server, such as Keycloak or Okta, and validates them. Set spring.security.oauth2.resourceserver.jwt.issuer-uri, and Boot discovers the public keys, then checks each token's signature, expiry and issuer. Scopes become SCOPE_ authorities for your rules.
- Login, passwords and tokens stay in the authorization server.
- Keys are fetched from the JWK (JSON Web Key) set and cached, so verifying is local.
- An opaque token is checked by introspection, a call per request.
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth.example/realms/shop See it in the infographic: A request through the security filter chain See it in the infographic: The parts of a JWT
A @PreAuthorize denial returns 500 instead of 403. What is the likely cause?
A catch-all @ExceptionHandler(Exception.class) in @RestControllerAdvice. A method rule fails inside the controller's proxy, so the access denied exception reaches the handlers of Spring MVC (Model-View-Controller) before it can reach ExceptionTranslationFilter. The advice catches it and returns 500. Add a handler that rethrows AccessDeniedException, or narrow the catch-all.
- URL rules in the filter chain are not affected, since they run before Spring MVC.
- With that advice, one token gets 403 from a URL rule and 500 from a method rule.
AuthorizationDeniedExceptionextendsAccessDeniedExceptionin current versions.
@ExceptionHandler(AccessDeniedException.class)
void denied(AccessDeniedException e) {
throw e; // let the security filters answer 403
} See it in the infographic: A request through the security filter chain
Why do many REST (Representational State Transfer) APIs disable CSRF (cross-site request forgery) protection, and when is that wrong?
CSRF abuses the cookies a browser attaches to a request by itself. An API that takes a bearer token in the Authorization header has no such cookie, because a forged request cannot add the header, so CSRF protection can go. If the API uses session cookies, including a browser app that stores its token in one, keep it on.
- The risk follows how credentials are sent, not the words "REST API".
- Pair
csrf.disable()withSTATELESSsession management. - CORS (cross-origin resource sharing) is a different thing, and it does not stop CSRF.
See it in the infographic: A request through the security filter chain
Check yourself
Show answers
- 403: Correct. Authentication succeeded, and authorization said no.
- 401: Incorrect. That is for missing or invalid credentials. This token is valid.
- 200: Incorrect. AuthorizationFilter stops the request before any controller.
Show answers
- Anyone who has the token: Correct. Base64URL is an encoding, not encryption. The signature only proves the content was not changed.
- Only a holder of the public key: Incorrect. The key verifies the signature. Reading the payload needs no key at all.
- Only the issuer: Incorrect. That would need an encrypted token. A signed token is plain text in Base64URL.
Show answers
- 403: Correct. The scope becomes SCOPE_admin, while hasRole looks for ROLE_ADMIN, and those are different strings.
- 200: Incorrect. Spring does not treat scopes and roles as the same thing.
- 401: Incorrect. The token is valid, so authentication passes. The rule fails afterward.