Quick revision
The short answer
We declare a @Bean method that takes HttpSecurity, permits /actuator/health, requires role ADMIN for /admin/**, requires authentication for everything else, configures oauth2ResourceServer with JWT, sets the session policy to STATELESS, disables CSRF because no cookies carry authentication, and returns http.build(). WebSecurityConfigurerAdapter is gone since Spring Security 6, and the rules are checked in order with the first match winning, so specific rules come before anyRequest().
What to remember
In this answer, we wrote a SecurityFilterChain bean for a stateless JWT API: /actuator/health public, /admin/** for role ADMIN and everything else authenticated, with oauth2ResourceServer validating tokens, a STATELESS session policy and CSRF disabled because no cookies carry authentication. We saw that rules are checked in order with the first match winning, verified the behaviour with spring-security-test, and mapped a roles claim to ROLE_ authorities so hasRole works.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We declare a @Bean method that takes HttpSecurity, permits /actuator/health, requires role ADMIN for /admin/**, requires authentication for everything else, configures oauth2ResourceServer with JWT, sets the session policy to STATELESS, disables CSRF because no cookies carry authentication, and returns http.build(). WebSecurityConfigurerAdapter is gone since Spring Security 6, and the rules are checked in order with the first match winning, so specific rules come before anyRequest().
Why this question is asked
Writing a SecurityFilterChain from memory is one of the most common practical tasks in Spring interviews, and the details matter: the order of rules, what hasRole really checks, why CSRF can be disabled here and not elsewhere. Interviewers use it to see whether we write current, correct configuration rather than code copied from an older version. In this answer, we will recap how the configuration style changed, write the bean, walk through each part and its reason, check it with tests, and answer the classic follow-up about mapping roles from the JWT.
1A Quick Recap: From the Adapter to a Bean
Before Spring Security 5.7, we configured security by extending WebSecurityConfigurerAdapter and overriding configure(HttpSecurity). That class was deprecated in 5.7 and removed in 6.0. Now we declare a SecurityFilterChain bean: a method that receives a pre-configured HttpSecurity builder from Spring, sets it up, and returns http.build().
A JWT, a JSON Web Token, is a signed token carrying claims such as the subject and scopes. Our service acts as a resource server: it does not log users in, it receives a bearer token in the Authorization header on each request, validates its signature and expiry, and builds an authentication from its claims.
2Writing the Bean
Here is the complete configuration for Spring Boot 3 or 4. The issuer is configured in properties, so Spring Boot can find the signing keys.
Notice the trailing comments: they are the four behaviours the question asks for, and they are also the four tests we will write.
3Walking Through Each Part
authorizeHttpRequests registers AuthorizationFilter with our rules. Rules are evaluated top to bottom and the first matching rule decides. If we put anyRequest().authenticated() first, it would match /actuator/health too, and the health check would need a token; Spring Security in fact refuses to start when anyRequest() is not last. So specific rules go first, the catch-all goes last.
oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) adds BearerTokenAuthenticationFilter and a JwtDecoder. Spring Boot creates the decoder from the issuer-uri property, fetching the issuer's public keys and checking the iss claim. A missing or invalid token produces a 401 with a WWW-Authenticate: Bearer header rather than a login redirect.
sessionManagement with STATELESS tells Spring Security never to create an HTTP session or store the context in one. Each request is authenticated from its own token, which is what a bearer token API wants: no session cookie, nothing to share between instances.
csrf(c -> c.disable()) is reasonable here, and only here. CSRF attacks work because browsers attach cookies automatically to cross-site requests. Our API authenticates with a header the browser never adds by itself, so a forged request from another site arrives without credentials. If the API ever accepted a session cookie or a token in a cookie, CSRF protection would have to come back.
- Bearer token present and valid?YesAuthenticated from JWT claimsNoAnonymous, or 401 if the token is invalid
- Path is /actuator/health?YesAllowNoCheck the next rule
- Path matches /admin/**?YesRequire ROLE_ADMIN, else 403NoCheck the next rule
- anyRequest: authenticated?YesAllowNo401 with WWW-Authenticate: Bearer
4 steps in order. Play them, or step through them one at a time.
Rules run top to bottom and the first match decides.
4Checking It With Tests
spring-security-test lets us simulate a JWT without a real identity provider. The jwt() request post-processor builds an authenticated request with the claims and authorities we choose.
Because the test slice runs the real SecurityFilterChain, these tests fail if someone reorders the rules or removes the STATELESS setting by mistake, which makes them a cheap safety net for every later change.
5Mapping Roles From the JWT
There is a catch with hasRole("ADMIN"). By default, Spring Security's JwtGrantedAuthoritiesConverter turns the token's scope or scp claim into authorities prefixed with SCOPE_, so a token with scope orders.read gives SCOPE_orders.read. hasRole("ADMIN") looks for ROLE_ADMIN, which a default token never produces. If our identity provider puts roles in a roles claim, we tell Spring Security to read that claim with the ROLE_ prefix.
Identity providers differ: Keycloak, for example, nests realm roles inside a realm_access object, which needs a small custom converter. Checking a real token's claims is the first step whenever an admin unexpectedly gets 403.
6Follow-up questions
How do role names map to authorities from the JWT?
By default the scope or scp claim becomes authorities with the SCOPE_ prefix, so roles are not mapped at all. hasRole("ADMIN") checks for the authority ROLE_ADMIN, so we configure a JwtGrantedAuthoritiesConverter that reads the claim holding roles and adds the ROLE_ prefix, either as a JwtAuthenticationConverter bean or, in recent Spring Boot versions, with the authorities-claim-name and authority-prefix properties. Alternatively we use hasAuthority("SCOPE_admin") if the provider expresses admin rights as a scope.
What is the difference between hasRole and hasAuthority?
hasAuthority checks the exact authority string. hasRole adds the ROLE_ prefix for us, so hasRole("ADMIN") is the same as hasAuthority("ROLE_ADMIN"). Passing "ROLE_ADMIN" to hasRole is an error in recent versions because the prefix would be doubled.
Why does an invalid token give 401 and not a redirect?
Because the resource server configures a BearerTokenAuthenticationEntryPoint, which responds with 401 and a WWW-Authenticate header describing the error, as the bearer token specification expects. A redirect to a login page only makes sense for browser form login, which this chain does not configure.
7Conclusion
In this answer, we wrote a SecurityFilterChain bean for a stateless JWT API: /actuator/health public, /admin/** for role ADMIN and everything else authenticated, with oauth2ResourceServer validating tokens, a STATELESS session policy and CSRF disabled because no cookies carry authentication. We saw that rules are checked in order with the first match winning, verified the behaviour with spring-security-test, and mapped a roles claim to ROLE_ authorities so hasRole works.
Open with
I would declare a SecurityFilterChain bean, because WebSecurityConfigurerAdapter was removed in Spring Security 6. The method takes HttpSecurity and in authorizeHttpRequests I add three rules in order: requestMatchers for /actuator/health with permitAll, /admin/** with hasRole ADMIN, and anyRequest authenticated.
Then, if they want more
Order matters because the first matching rule wins, so the catch-all goes last; Spring Security actually refuses anyRequest anywhere else. Then oauth2ResourceServer with jwt and Customizer.withDefaults, plus the issuer-uri property, so Spring Boot builds a JwtDecoder that validates signature, expiry and issuer, and invalid or missing tokens get a 401 with a WWW-Authenticate Bearer header.
Session management is STATELESS, so no HTTP session is created and each request is authenticated by its own token. I disable CSRF, which is safe here because the browser never sends the bearer header automatically; if we ever authenticated with cookies, it would have to come back. Finally I return http.build().
One thing to watch is role mapping: by default the JWT's scope claim becomes SCOPE_ authorities, and hasRole ADMIN checks ROLE_ADMIN, so I configure a JwtGrantedAuthoritiesConverter to read the roles claim with the ROLE_ prefix, and I cover all four cases with spring-security-test using jwt().
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 3, Spring Security 5, Spring Security 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Security reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a SecurityFilterChain bean for a Spring Boot 3 or 4 service where /actuator/health...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/a7df7e16de/