Separating JWT API and session admin chains in Spring Security
Run stateless JWT REST APIs and session-based admin pages in one Spring Boot app using multiple SecurityFilterChain beans with @Order and securityMatcher.
Running a stateless JWT REST API alongside a session-based admin console inside one Spring Boot app creates immediate policy conflicts. This post shows how I isolate them cleanly using multiple
SecurityFilterChainbeans ordered with@Orderand scoped withsecurityMatcher.
The problem: authentication conflicts in a single filter chain
Many backend projects serve both a REST API (for mobile apps or SPAs) and an internal Admin Web console from the same Spring Boot deployment. If you try to handle both inside a single SecurityFilterChain, their requirements clash in three places:
flowchart TD
A["Mobile / SPA (/api/**)"] --> C["Single SecurityFilterChain"]
B["Admin browser (/admin/**)"] --> C
C --> D["Session conflict: STATELESS JWT vs. cookie session"]
C --> E["Error conflict: JSON 401 vs. 302 login redirect"]
C --> F["CSRF conflict: disabled for API vs. required for forms"]
- Session policy: REST APIs need strict statelessness (
STATELESS) withAuthorization: Bearer <token>headers, while the admin UI relies on form login and browser session cookies (IF_REQUIRED). - Authentication error responses: A mobile client calling an API without a token expects a structured JSON
401 Unauthorizedresponse. A single chain configured with form login returns a302redirect to/admin/logininstead, breaking JSON parsers on the client. - CSRF protection: Stateless Bearer-token APIs don’t send credential cookies, so CSRF protection is disabled. Session-backed admin forms send cookies on every request and require CSRF tokens.
Spring Security solves this cleanly with multiple SecurityFilterChain beans.
Designing the filter chains with @Order and securityMatcher
When an HTTP request arrives, FilterChainProxy walks through every registered SecurityFilterChain bean in @Order order (lower numbers first). The first chain whose securityMatcher matches the request URL runs, and none of the remaining chains execute.
flowchart TD
Req["Incoming HTTP request"] --> Proxy["FilterChainProxy"]
Proxy --> C0{"@Order(0)<br/>/swagger-ui/**, /v3/api-docs/**"}
C0 -->|"Match"| ChainSwagger["Swagger chain<br/>(permitAll, CSRF disabled)"]
C0 -->|"No match"| C1{"@Order(1)<br/>/api/v1/auth/social/**"}
C1 -->|"Match"| ChainSocial["Social OAuth2 chain<br/>(cookie-based OAuth2 state)"]
C1 -->|"No match"| C2{"@Order(2)<br/>/api/**"}
C2 -->|"Match"| ChainApi["API chain (stateless JWT)<br/>NullSecurityContextRepository + JSON 401/403"]
C2 -->|"No match"| C3{"@Order(3)<br/>/admin/**"}
C3 -->|"Match"| ChainAdmin["Admin web chain (formLogin)<br/>IF_REQUIRED + changeSessionId + CSRF"]
C3 -->|"No match"| CFallback["@Order(LOWEST_PRECEDENCE)<br/>Fallback chain (denyAll except static/error/actuator)"]
Always put narrower, more specific matchers first. If /api/** had a lower @Order number than /api/v1/auth/social/**, the general API chain would intercept social login callbacks before the OAuth2 chain ever saw them.
Shared beans, Swagger chain, and defensive fallback chain
Start by defining the shared PasswordEncoder and AuthenticationManager, along with the top-priority Swagger chain and the lowest-priority fallback chain.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// src/main/kotlin/com/example/server/security/SecurityConfig.kt
package com.example.server.security
import com.example.server.security.user.DomainUserDetailsService
import org.springframework.beans.factory.ObjectProvider
import org.springframework.boot.h2console.autoconfigure.H2ConsoleProperties
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.ProviderManager
import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.SecurityFilterChain
@Configuration
class SecurityConfig {
@Bean
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
@Bean
fun authenticationManager(
userDetailsService: DomainUserDetailsService,
passwordEncoder: PasswordEncoder,
): AuthenticationManager {
val provider = DaoAuthenticationProvider(userDetailsService).apply {
setPasswordEncoder(passwordEncoder)
}
return ProviderManager(provider)
}
@Bean
@Order(0)
fun swaggerFilterChain(http: HttpSecurity): SecurityFilterChain {
http.securityMatcher("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**")
.csrf { it.disable() }
.authorizeHttpRequests { it.anyRequest().permitAll() }
return http.build()
}
@Bean
@Order(Ordered.LOWEST_PRECEDENCE)
fun fallbackFilterChain(
http: HttpSecurity,
h2ConsoleProperties: ObjectProvider<H2ConsoleProperties>,
): SecurityFilterChain {
val h2Console = h2ConsoleProperties.ifAvailable?.let { PathRequest.toH2Console() }
http
.authorizeHttpRequests {
it.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
h2Console?.let { matcher -> it.requestMatchers(matcher).permitAll() }
it.requestMatchers("/error", "/actuator/**").permitAll()
it.anyRequest().denyAll()
}
.csrf { csrf -> h2Console?.let { csrf.ignoringRequestMatchers(it) } }
.headers { headers -> headers.frameOptions { it.sameOrigin() } }
return http.build()
}
}
API chain: stateless JWT and NullSecurityContextRepository
The REST API chain has two strict goals: zero session usage and JSON-only error responses.
Setting SessionCreationPolicy.STATELESS alone still leaves room for Spring Security to read an existing SecurityContext if a browser happens to send an admin session cookie on an /api/** request. Wiring NullSecurityContextRepository() explicitly prevents the chain from reading or storing any session-backed security context.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// src/main/kotlin/com/example/server/security/api/ApiSecurityConfig.kt
package com.example.server.security.api
import com.example.server.security.jwt.JwtProvider
import com.example.server.user.domain.UserRole
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.context.NullSecurityContextRepository
@Configuration
class ApiSecurityConfig(
private val apiSecurityHandlers: ApiSecurityHandlers,
) {
@Bean
@Order(2)
fun apiFilterChain(http: HttpSecurity): SecurityFilterChain {
http.securityMatcher("/api/**")
.csrf { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.securityContext { it.securityContextRepository(NullSecurityContextRepository()) }
.requestCache { it.disable() }
.authorizeHttpRequests {
it.requestMatchers(
HttpMethod.POST,
"/api/v1/auth/login",
"/api/v1/auth/join",
"/api/v1/auth/refresh",
).permitAll()
it.requestMatchers("/api/v1/admin/**").hasRole(UserRole.ADMIN.name)
it.anyRequest().authenticated()
}
.oauth2ResourceServer { resourceServer ->
resourceServer.jwt { it.jwtAuthenticationConverter(jwtAuthenticationConverter()) }
resourceServer.authenticationEntryPoint(apiSecurityHandlers)
resourceServer.accessDeniedHandler(apiSecurityHandlers)
}
.exceptionHandling {
it.authenticationEntryPoint(apiSecurityHandlers)
it.accessDeniedHandler(apiSecurityHandlers)
}
return http.build()
}
private fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
val authoritiesConverter = JwtGrantedAuthoritiesConverter().apply {
setAuthoritiesClaimName(JwtProvider.ROLES_CLAIM)
setAuthorityPrefix(UserRole.ROLE_PREFIX)
}
return JwtAuthenticationConverter().apply {
setJwtGrantedAuthoritiesConverter(authoritiesConverter)
}
}
}
JSON error handlers for 401 and 403
To return consistent JSON bodies and a WWW-Authenticate: Bearer header instead of redirecting to an HTML login page, implement both AuthenticationEntryPoint and AccessDeniedHandler in ApiSecurityHandlers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/server/security/api/ApiSecurityHandlers.kt
package com.example.server.security.api
import com.example.server.auth.AuthErrorCode
import com.example.server.common.ApiResponse
import com.example.server.common.ErrorCode
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.AuthenticationEntryPoint
import org.springframework.security.web.access.AccessDeniedHandler
import org.springframework.stereotype.Component
import tools.jackson.databind.json.JsonMapper
@Component
class ApiSecurityHandlers(
private val jsonMapper: JsonMapper,
) : AuthenticationEntryPoint, AccessDeniedHandler {
override fun commence(
request: HttpServletRequest,
response: HttpServletResponse,
authException: AuthenticationException,
) {
val errorCode = AuthErrorCode.UNAUTHORIZED
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer")
write(response, errorCode)
}
override fun handle(
request: HttpServletRequest,
response: HttpServletResponse,
accessDeniedException: AccessDeniedException,
) {
write(response, AuthErrorCode.ACCESS_DENIED)
}
private fun write(response: HttpServletResponse, errorCode: ErrorCode) {
response.status = errorCode.status.value()
response.contentType = MediaType.APPLICATION_JSON_VALUE
response.characterEncoding = Charsets.UTF_8.name()
jsonMapper.writeValue(response.outputStream, ApiResponse.error(errorCode))
}
}
Calling an API endpoint without a Bearer token now returns a JSON 401 immediately rather than redirecting to the admin login page.
Figure 1. Unauthenticated API request returning a structured JSON 401 response.
Admin web chain: session form login and CSRF
The admin web chain uses standard browser sessions with form login, keeping CSRF enabled by default:
- Session fixation protection:
changeSessionId()rotates the session ID right after login so a pre-login cookie cannot be hijacked. - CSRF validation: Thymeleaf’s
th:actioninjects the hidden_csrffield automatically, and Spring Security validates it on every state-changing POST. - HTML error routing: Unauthenticated requests go to
/admin/loginviaLoginUrlAuthenticationEntryPoint, and forbidden requests render/admin/403.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// src/main/kotlin/com/example/server/security/admin/AdminWebSecurityConfig.kt
package com.example.server.security.admin
import com.example.server.config.SessionConfig
import com.example.server.user.domain.UserRole
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.annotation.Order
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint
@Configuration
class AdminWebSecurityConfig {
@Bean
@Order(3)
fun adminWebFilterChain(http: HttpSecurity): SecurityFilterChain {
http
.securityMatcher("/admin/**")
.authorizeHttpRequests {
it.requestMatchers("/admin/login", "/admin/403").permitAll()
it.anyRequest().hasRole(UserRole.ADMIN.name)
}
.formLogin {
it.loginPage(LOGIN_PAGE)
it.loginProcessingUrl(LOGIN_PAGE)
it.defaultSuccessUrl("/admin/dashboard")
it.failureUrl("$LOGIN_PAGE?error")
it.permitAll()
}
.exceptionHandling {
it.authenticationEntryPoint(LoginUrlAuthenticationEntryPoint(LOGIN_PAGE))
it.accessDeniedPage("/admin/403")
}
.sessionManagement {
it.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
it.sessionFixation { fixation -> fixation.changeSessionId() }
it.invalidSessionUrl("$LOGIN_PAGE?expired")
}
.logout {
it.logoutUrl("/admin/logout")
it.logoutSuccessUrl("$LOGIN_PAGE?logout")
it.invalidateHttpSession(true)
it.clearAuthentication(true)
it.deleteCookies(SessionConfig.SESSION_COOKIE_NAME)
}
return http.build()
}
companion object {
const val LOGIN_PAGE = "/admin/login"
}
}
After a successful admin login, the browser receives Set-Cookie: SESSION=...; HttpOnly; SameSite=Lax and redirects to /admin/dashboard.
Figure 2. Admin login response setting the HttpOnly session cookie and redirecting to the dashboard.
Verifying chain isolation with MockMvc
You can prove both chains stay isolated with MockMvc integration tests.
1. API chain: stateless auth and JSON 401
A valid Bearer JWT must authenticate without issuing Set-Cookie or writing SPRING_SECURITY_CONTEXT into a session, and a missing token must return JSON 401.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/test/kotlin/com/example/server/security/ApiSecurityTest.kt
package com.example.server.security
import com.example.server.support.IntegrationTestSupport
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.http.HttpHeaders
import org.springframework.test.web.servlet.get
@DisplayName("API chain (stateless JWT)")
class ApiSecurityTest : IntegrationTestSupport() {
@Test
fun `authenticates with a valid JWT without creating a session`() {
val user = createUser()
mockMvc.get("/api/v1/users/me") {
header(HttpHeaders.AUTHORIZATION, "Bearer ${accessTokenOf(user)}")
}.andExpect {
status { isOk() }
jsonPath("$.data.id") { value(user.id.toString()) }
header { doesNotExist(HttpHeaders.SET_COOKIE) }
request { sessionAttributeDoesNotExist("SPRING_SECURITY_CONTEXT") }
}
}
@Test
fun `returns JSON 401 instead of a login redirect when JWT is missing`() {
mockMvc.get("/api/v1/users/me").andExpect {
status { isUnauthorized() }
content { contentTypeCompatibleWith("application/json") }
jsonPath("$.success") { value(false) }
jsonPath("$.code") { value("AUTH-000") }
header { string(HttpHeaders.WWW_AUTHENTICATE, "Bearer") }
}
}
}
Passing the same Bearer token in Swagger UI returns 200 OK with no session state created.
Figure 3. Swagger UI calling an authenticated API endpoint with a JWT Bearer token.
2. Admin chain: login redirect and session ID rotation
Unauthenticated requests to /admin/dashboard must redirect to /admin/login, and submitting valid credentials must rotate the session ID and store the authenticated principal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/test/kotlin/com/example/server/security/AdminWebSecurityTest.kt
package com.example.server.security
import com.example.server.security.user.AuthUser
import com.example.server.support.IntegrationTestSupport
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
@DisplayName("Admin web chain (session formLogin)")
class AdminWebSecurityTest : IntegrationTestSupport() {
@Test
fun `redirects unauthenticated users to the login page`() {
mockMvc.get("/admin/dashboard").andExpect {
status { is3xxRedirection() }
redirectedUrl("/admin/login")
}
}
@Test
fun `rotates the session ID on login and stores the principal in the session`() {
val admin = createAdmin()
val anonymousCookie = mockMvc.get("/admin/login").andReturn().sessionCookie()!!
val result = mockMvc.post("/admin/login") {
with(csrf())
cookie(anonymousCookie)
param("username", admin.email!!)
param("password", PASSWORD)
}.andExpect {
status { is3xxRedirection() }
redirectedUrl("/admin/dashboard")
}.andReturn()
val sessionCookie = result.sessionCookie()!!
assertThat(sessionCookie.value).isNotEqualTo(anonymousCookie.value)
assertThat(sessionCookie.isHttpOnly).isTrue()
val principal = securityContextOf(sessionCookie)?.authentication?.principal
assertThat(principal).isInstanceOf(AuthUser::class.java)
assertThat((principal as AuthUser).id).isEqualTo(admin.id)
}
}
Trade-offs and checklist
Multiple filter chains keep a monolith simple, but they aren’t always the right boundary. If your admin console grows its own deployment cadence, heavy reporting queries, or strict network isolation requirements (VPN-only access), splitting it into a separate Spring Boot service is safer than adding more security chains to the same process.
When you do keep both in one app, verify these four items before shipping:
- Order narrow matchers first: Arrange
@Orderfrom most specific to broadest (Swagger→OAuth Callback→/api/**→/admin/**→Fallback) so broader chains never shadow narrower ones. - Seal the API chain against sessions: Pair
SessionCreationPolicy.STATELESSwithNullSecurityContextRepository()so admin browser cookies can’t bleed into/api/**. - Separate error handlers per chain: Return structured JSON +
WWW-Authenticate: Beareron/api/**and HTML login redirects on/admin/**. - Default to
denyAll()in the fallback chain: Keep an@Order(Ordered.LOWEST_PRECEDENCE)chain that permits only known public assets and denies every unmatched route by default.