The labs on this site need JavaScript to run. The same content is written out below.
Learn › Spring › Other features
Security filter chain
Where is it decided whether the response is 401 or 403?
Why it exists — If code that checks login status and permissions is put directly in each controller, missing just one place leaves that path open. Spring Security gathers this check in the filter stage in front of the controllers, so that when rules for each path are written in one place in the configuration, they are applied to all requests in the same way.
Where it's used today — It is used in web services and API servers that require login. An API server that verifies users with a JWT turns on the token-checking filter with one line of oauth2ResourceServer configuration, and writes the rule that lets only the ADMIN authority through on admin paths in authorizeHttpRequests. When checking permissions per controller method, annotations such as @PreAuthorize are used together.
Spring Security is a line of filters placed in front of the controller. A filter near the front checks "who this is" and records it in the SecurityContext, and a filter near the back decides "whether this user may enter this path". For an API server that uses a JWT, the oauth2ResourceServer configuration that Spring Security provides adds the token-checking filter (BearerTokenAuthenticationFilter) together with the parts that make the 401 and 403 responses. The response is 401 when the user is not identified, and 403 when the user is identified but lacks the required authority. This lab shows where a request is stopped, and with which response it ends, depending on its token and path.
Checked against real execution · The 12 requests were sent to a Spring Boot 4.1.1 and Spring Security 7.1.1 resource server (oauth2-resource-server 7.1.1, nimbus-jose-jwt 10.9.1) started with the configuration code on the screen as it is, and the response codes, the places that produced the responses, whether the controller ran, and the order of the filters passed were checked. The expiration time of the tokens was set to 10 minutes after the time of the run
Concepts in this lab
- Authentication and authorization
- Authentication checks who a user is. Authorization decides whether that verified user has permission to use a specific resource or feature. Authentication happens first, and authorization is decided based on its result. In HTTP status codes, a failed authentication corresponds to 401 and a failed authorization corresponds to 403.
- Spring Security and SecurityFilterChain
- Why it exists — If you wrote security checks yourself as Servlet filters, you had to arrange by hand, in every project, the order and the URLs of the filters for login checks, permission checks, and CSRF checks. Spring Security provides such filters in a fixed order, and SecurityFilterChain lets you choose which check to use for which URL.
- Where it's used today — You configure form login, JWT verification, social login, and restrictions on admin URLs in a SecurityFilterChain bean. For groups with different rules, such as /api/** URLs and page URLs, you use more than one chain to split them.
- Spring Security is Spring's security framework for handling authentication and authorization, and it works as a set of Servlet filters. A SecurityFilterChain defines which security filters apply to which requests and in what order. Before a request reaches the controller, the filters run one after another and do work such as checking the authentication information and checking permissions.
- OAuth 2.0 resource server (oauth2ResourceServer)
- Why it exists — Each API server that verifies users with a JWT wrote its own filters for reading the Authorization header, verifying the token, recording the authentication information, and sending the failure response, and mistakes such as letting a wrong token pass or leaving out a response header were common. This feature lets you turn on that work, which follows the OAuth 2.0 Bearer token specification (RFC 6750), with one line of configuration.
- Where it's used today — It is used in a REST API server that receives JWT access tokens. If the authorization server publishes a list of public keys, the spring.security.oauth2.resourceserver.jwt.issuer-uri or jwk-set-uri property alone is enough to create the JwtDecoder, and if you use a symmetric key (HS256), you register a JwtDecoder bean created with NimbusJwtDecoder.withSecretKey yourself.
- In OAuth 2.0, the server that accepts access tokens and serves an API is called a resource server. In Spring Security, you turn this role on by writing http.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) in the SecurityFilterChain configuration (spring-boot-starter-oauth2-resource-server is needed). Then BearerTokenAuthenticationFilter, which checks the token in the Authorization: Bearer header, is added to the chain. If there is no token, it simply passes the request on to the next filter. If there is one, it verifies it with a JwtDecoder, and if that succeeds, it puts a JwtAuthenticationToken into the SecurityContext, and if it fails, it ends the request right there with 401 whatever the path. JwtAuthenticationConverter turns the claims of the token into authorities, and by default it makes an authority with the prefix SCOPE_ for each value of the scope (or scp) claim. The response parts for an authentication failure and for a lack of authority (BearerTokenAuthenticationEntryPoint and BearerTokenAccessDeniedHandler) are registered together with it.
- SecurityContext
- Why it exists — To pass the user identified in a filter on to the controller and the service, you would have to pass the user information as a parameter of every method. With a SecurityContext, you can get the current user through SecurityContextHolder in any layer that handles the same request, without passing it that way.
- Where it's used today — The @AuthenticationPrincipal parameter of a controller and the @PreAuthorize check on a method use the authentication information held here. When execution moves to another thread, as with @Async, it is not carried over by default, so you must pass it separately.
- The place where Spring Security keeps the authentication information of the user who sent the current request (who the user is and what permissions the user has). When authentication succeeds, the information is stored here. Later, controllers and services read it from here to look up the current user. By default, it is kept per thread.
- Servlet filter
- Where it's used today — In Spring Boot, you apply one by extending OncePerRequestFilter and registering it as a bean. Use it for work unrelated to controllers, such as request logging or attaching a request number, and if you need to know which controller method is involved, an interceptor is the right choice.
- This component intercepts and processes requests and responses at the servlet container level, and it is part of the Servlet standard. It acts before a request reaches DispatcherServlet and on the way back of the response, and it is used for work that spans all requests, such as setting the encoding, handling CORS, and authentication. Spring Security also works as a group of these components.
- AuthenticationEntryPoint and AccessDeniedHandler
- Why it exists — The refusal response cannot be created in a controller. This decision is made in a filter before the request reaches DispatcherServlet, so @ControllerAdvice does not reach it. So a separate place for creating the response was provided at the filter stage, so that it can be swapped out.
- Where it's used today — To make the body of the 401 and 403 responses of an API server a JSON error format, you pass your own implementations with http.exceptionHandling(e -> e.authenticationEntryPoint(…).accessDeniedHandler(…)) or oauth2ResourceServer(o -> o.authenticationEntryPoint(…).accessDeniedHandler(…)). If a handler uses sendError, the request is passed on to /error and goes through the security rules of that path once more, so you write the status code directly or permit /error.
- These are the two interfaces by which Spring Security creates the response when it refuses a request. AuthenticationEntryPoint is called when "it has not been confirmed who this is" and usually answers with 401 (or, for form login, sends the user to the login page), and AccessDeniedHandler is called when "the user is authenticated but lacks the authority" and answers with 403. The one that chooses between them is ExceptionTranslationFilter: when the AuthorizationFilter behind it throws an access denied exception, it looks at whether the current user is anonymous, and calls the entry point if so and the handler if not. oauth2ResourceServer registers BearerTokenAuthenticationEntryPoint (401 and a WWW-Authenticate: Bearer header) and BearerTokenAccessDeniedHandler (403 and error="insufficient_scope") by default.
- HTTP status codes
- Why it exists — If results were reported only as text in the body, each server would write them differently, and browsers, proxies, and monitoring tools could not tell whether a request succeeded. A status code reports the result as a fixed number, so these tools can do caching, retries, and error counting without being adjusted for each server.
- Where it's used today — It is used to branch handling by the kind of error, such as a frontend that sends the user to the login screen on a 401 and to a "page not found" notice on a 404. In operations, you watch the ratio of 5xx responses and, if it suddenly rises, treat it as an outage and send an alert.
- A three-digit number that shows the result of the server's handling of a request. 2xx means success, 3xx means a move to another location (redirection), 4xx means a problem with the client's request, and 5xx means an error on the server side. Common ones are 200 (success), 201 (created), 400 (bad request), 401 (authentication required), 403 (no permission), 404 (not found), and 500 (server error).
Try these
- Default settings — A path that requires login is requested without a token. 401.
- With a valid token — The request reaches the controller.
- USER requests an admin path — It is known who the user is, but the user lacks the authority. 403.
- ADMIN requests an admin path — The request passes.
- Admin path without a token — The response is 401, not 403. See why.
- Path permitted for everyone, with a forged token — The response is 401 even though it is a permitAll path.
- Path permitted for everyone, without a token — The request passes even without a token.
Running with the default settings
- GET /orders comes in and enters the security filter chain. This is the Servlet filter stage, which comes before the controller.
- BearerTokenAuthenticationFilter: There is no Bearer token in the Authorization header. The filter does nothing and passes the request on to the next filter. It does not reject the request right here because the path may be one that does not require authentication.
- AnonymousAuthenticationFilter: If there is still no authentication information at this point, the filter marks the request as coming from an "anonymous user".
- AuthorizationFilter: The rule for this path is authenticated (authenticated users only). The current user is anonymous, so the condition is not met. The filter throws an access denied exception (AccessDeniedException).
- ExceptionTranslationFilter: The filter catches the exception and checks the user. The user is anonymous, so the filter treats this not as "no authority" but as "say who you are first", and it calls the AuthenticationEntryPoint. The BearerTokenAuthenticationEntryPoint that oauth2ResourceServer registered responds with 401 and a WWW-Authenticate: Bearer header.
- The response goes out, and the SecurityContext that was used for this request is cleared. The information is bound to the thread, so it must be removed before the thread is reused for the next request.
Result of this run
- 401 means "it has not been confirmed who this is" (authentication failed). A request for an admin path without a token gets 401, not 403, because ExceptionTranslationFilter turns the access denial of an anonymous user into "say who you are first". oauth2ResourceServer registers BearerTokenAuthenticationEntryPoint as the entry point used for this, so 401 comes out even if you do not write exceptionHandling separately.
- This response is produced in a filter before the request reaches DispatcherServlet, so it cannot be changed with @ControllerAdvice. To change the format of the response, pass other implementations with oauth2ResourceServer(o -> o.authenticationEntryPoint(…).accessDeniedHandler(…)).
Code
// Only the configuration class body is shown (@Configuration class declaration and imports omitted)
// oauth2ResourceServer, JwtDecoder, NimbusJwtDecoder, JwtAuthenticationConverter,
// and JwtGrantedAuthoritiesConverter are provided by Spring Security (spring-boot-starter-oauth2-resource-server).
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // adds BearerTokenAuthenticationFilter
.build();
}
@Bean // the decoder that checks the signature of the token (HS256, the key is at least 32 bytes)
JwtDecoder jwtDecoder(@Value("${app.jwt.secret}") String secret) { // app.jwt.secret is a setting name chosen for this example
SecretKey key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
return NimbusJwtDecoder.withSecretKey(key).build();
}
@Bean // turns the role claim ("USER") of the token into the authority ROLE_USER (by default, the scope claim becomes SCOPE_ authorities)
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("role");
roles.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
return converter;
}
// The 401 and 403 responses are made by BearerTokenAuthenticationEntryPoint and
// BearerTokenAccessDeniedHandler, which oauth2ResourceServer registers by default (you do not need to write exceptionHandling separately).
Assumptions of this model
The model assumes a JWT API server that does not use sessions and uses oauth2ResourceServer of Spring Security with an HS256 JwtDecoder. The configuration code on the screen was turned into a configuration class as it is, on a server running Spring Boot 4.1.1 and Spring Security 7.1.1 (spring-security-oauth2-resource-server and oauth2-jose 7.1.1, nimbus-jose-jwt 10.9.1). HTTP requests for all 12 combinations were sent to it, and it was confirmed that the response code, the place that produced the response, whether the controller ran, and the order of the filters that the request passes match the screen. BearerTokenAuthenticationFilter, BearerTokenAuthenticationEntryPoint, and BearerTokenAccessDeniedHandler, which oauth2ResourceServer adds, really ran. Which part produced the response was confirmed from the call stack at the moment the status code was set, and the authorization decision and the authentication at that moment were confirmed from the authorization events (AuthorizationEvent) that Spring Security publishes. On the same server I also confirmed that a wrong token ends in the token-checking filter with 401 whatever the path, that the 403 response is not dispatched again to the error page, that 401 and 403 do not reach @ControllerAdvice, that the SecurityContext is cleared after the response, and that the responses change to the given implementations when a different entry point and handler are passed to oauth2ResourceServer. The tokens have the same shape as in the lab "JWT structure and verification" (HS256, member 7, role), but the decoder measures expiration with the system clock, so their expiration time was set to 10 minutes after the time of the run. The forged token is one whose role in the payload was changed to ADMIN while the signature was left as it was. In 7.1.1, the WWW-Authenticate header of the response to a request with no token or a wrong token also carries a resource_metadata value. From 7.0 on, JwtAuthenticationConverter adds one more authority, FACTOR_BEARER, besides the authorities made from role, but this does not affect the rules of this lab. A real chain has more filters that are not listed here.
Previous lab: Cache abstraction