Spring › Feature

Testing JWT and session security chains with Spring MockMvc

Go beyond @WithMockUser by testing real Bearer tokens, session cookies, CSRF checks, and cross-chain isolation across dual Spring Security filter chains.

Testing JWT and session security chains with Spring MockMvc

Annotating a test with @WithMockUser bypasses the exact Spring Security filters that fail in production. This post shows how I test a dual SecurityFilterChain app—stateless JWT API plus session-based Admin Web—using real signed tokens, Redis session lookups, and MockMvc Kotlin DSL.

Tested with Spring Boot 3.4, Spring Security 6.4, Spring Session Data Redis, and Kotlin 2.1.

Why @WithMockUser misses dual-chain security bugs

When you run a stateless JWT resource server (/api/**) alongside a browser-session admin console (/admin/**) in the same Spring Boot app (as in my dual SecurityFilterChain setup), @WithMockUser gives false confidence.

flowchart TD
    subgraph MockApproach["@WithMockUser Shortcut"]
        A1["Test injects mock Authentication<br/>into TestSecurityContextHolder"] --> A2["Bypasses real security filters"]
        A2 --> A3["Misses bad tokens, CSRF,<br/>and session leaks"]
    end
    subgraph RealFlow["Full MockMvc Filter Test"]
        B1["Send real Bearer header or Cookie"] --> B2["FilterChainProxy matches URL chain"]
        B2 --> B3["Runs JwtDecoder / CsrfFilter /<br/>SessionCreationPolicy"]
        B3 --> B4["Proves 401/403 format and<br/>cross-chain isolation"]
    end

Relying on @WithMockUser leaves three blind spots:

  1. Authentication filters never run: @WithMockUser pre-populates TestSecurityContextHolder before the servlet filter chain executes. Signature tampering, expiration checks, and custom JwtDecoder errors never get exercised.
  2. Stateless session leaks go undetected: An API chain configured with SessionCreationPolicy.STATELESS and NullSecurityContextRepository must never emit a Set-Cookie header. Mocked security contexts don’t prove that a misconfigured filter isn’t creating sessions.
  3. Cross-chain isolation stays unproven: You can’t verify that an admin SESSION cookie gets rejected on /api/** with 401, or that a mobile Bearer token gets redirected to /admin/login on /admin/**.

To catch these before deployment, drive requests through the real FilterChainProxy with actual HTTP headers and cookies.


Base test setup: IntegrationTestSupport

I use a shared @SpringBootTest + @AutoConfigureMockMvc base class backed by an in-memory database and local Redis. It injects the real JwtProvider and Spring Session’s SessionRepository so tests can mint signed tokens and inspect serialized SecurityContext objects directly in Redis.

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
65
66
// src/test/kotlin/com/example/server/support/IntegrationTestSupport.kt
package com.example.server.support

import com.example.server.security.jwt.JwtProvider
import com.example.server.security.user.AuthUser
import com.example.server.user.domain.User
import com.example.server.user.domain.UserRepository
import com.example.server.user.domain.UserRole
import jakarta.servlet.http.Cookie
import java.util.Base64
import java.util.UUID
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.session.Session
import org.springframework.session.SessionRepository
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.MvcResult

@SpringBootTest(properties = ["app.jobs.scheduling-enabled=false"])
@AutoConfigureMockMvc
abstract class IntegrationTestSupport {

    @Autowired protected lateinit var mockMvc: MockMvc
    @Autowired protected lateinit var userRepository: UserRepository
    @Autowired protected lateinit var passwordEncoder: PasswordEncoder
    @Autowired protected lateinit var jwtProvider: JwtProvider
    @Autowired private lateinit var sessionRepository: SessionRepository<out Session>

    protected fun createUser(
        password: String? = PASSWORD,
        roles: Set<UserRole> = setOf(UserRole.USER),
        email: String? = "user-${UUID.randomUUID()}@example.com",
        nickname: String = "tester",
    ): User = userRepository.save(
        User(
            email = email,
            password = password?.let { passwordEncoder.encode(it) },
            nickname = nickname,
            roles = roles.toMutableSet(),
        )
    )

    /** Mint a real signed Access Token using the app's configured signing key. */
    protected fun accessTokenOf(user: User): String =
        jwtProvider.createAccessToken(AuthUser.from(user))

    /** Extract a non-expired SESSION cookie from the MockMvc response. */
    protected fun MvcResult.sessionCookie(): Cookie? =
        response.getCookie(SESSION_COOKIE)?.takeIf { it.maxAge != 0 && it.value.isNotEmpty() }

    /** Decode the Base64 session cookie and load the stored SecurityContext from Redis. */
    protected fun securityContextOf(cookie: Cookie): SecurityContext? {
        val sessionId = String(Base64.getDecoder().decode(cookie.value))
        return sessionRepository.findById(sessionId)
            ?.getAttribute<SecurityContext>(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)
    }

    companion object {
        const val PASSWORD = "password123!"
        const val SESSION_COOKIE = "SESSION"
    }
}

Three design choices make this base class pull its weight:

  • Real signing and decoding: accessTokenOf delegates to the app’s own JwtProvider, so JwtDecoder and JwtAuthenticationProvider verify signatures, expiration timestamps, and custom claims identically to production.
  • Direct Redis session inspection: Injecting SessionRepository lets tests decode the Base64 SESSION cookie and inspect the exact SecurityContext stored in Redis, confirming that AuthUser deserializes cleanly without retaining password hashes.
  • MockMvc Kotlin DSL: Using Spring’s official mockMvc.get(...) { ... }.andExpect { ... } DSL avoids verbose MockMvcRequestBuilders chaining and keeps security assertions scannable.

Testing the stateless JWT API chain

The API chain must authenticate valid Bearer tokens, return structured JSON 401 responses on failure, create zero sessions, and ignore admin cookies.

sequenceDiagram
    autonumber
    actor Client as "Mobile Client"
    participant Filter as "BearerTokenAuthenticationFilter"
    participant Auth as "JwtAuthenticationProvider"
    participant Repo as "NullSecurityContextRepository"
    Client->>Filter: GET /api/v1/users/me (Bearer token)
    alt Valid token
        Filter->>Auth: Verify signature, expiry, claims
        Auth-->>Filter: JwtAuthenticationToken
        Filter->>Repo: Save context (no-op)
        Filter-->>Client: 200 OK (no Set-Cookie)
    else Missing, tampered, or expired
        Filter-->>Client: 401 Unauthorized (JSON error code)
    end
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// src/test/kotlin/com/example/server/security/ApiSecurityTest.kt
package com.example.server.security

import com.example.server.support.IntegrationTestSupport
import com.example.server.user.domain.UserRole
import java.time.Instant
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.http.HttpHeaders
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("API chain (JWT, stateless)")
class ApiSecurityTest : IntegrationTestSupport() {

    @Test
    fun `valid JWT authenticates 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 `missing, tampered, and expired JWTs return specific 401 codes`() {
        // 1. Missing token -> AUTH-000
        mockMvc.get("/api/v1/users/me").andExpect {
            status { isUnauthorized() }
            content { contentTypeCompatibleWith("application/json") }
            jsonPath("$.code") { value("AUTH-000") }
            header { string(HttpHeaders.WWW_AUTHENTICATE, "Bearer") }
        }

        // 2. Tampered signature -> AUTH-001
        val token = accessTokenOf(createUser())
        val tampered = token.dropLast(4) + if (token.endsWith("AAAA")) "BBBB" else "AAAA"
        mockMvc.get("/api/v1/users/me") {
            header(HttpHeaders.AUTHORIZATION, "Bearer $tampered")
        }.andExpect {
            status { isUnauthorized() }
            jsonPath("$.code") { value("AUTH-001") }
        }

        // 3. Expired token -> AUTH-002
        val user = createUser()
        val expired = jwtProvider.createAccessToken(
            userId = user.id!!,
            roles = listOf(UserRole.USER.name),
            issuedAt = Instant.now().minusSeconds(7200),
        )
        mockMvc.get("/api/v1/users/me") {
            header(HttpHeaders.AUTHORIZATION, "Bearer $expired")
        }.andExpect {
            status { isUnauthorized() }
            jsonPath("$.code") { value("AUTH-002") }
        }
    }

    @Test
    fun `admin session cookie does not authenticate API requests`() {
        val admin = createUser(roles = setOf(UserRole.ADMIN, UserRole.USER))
        val sessionCookie = mockMvc.post("/admin/login") {
            with(csrf())
            param("username", admin.email!!)
            param("password", PASSWORD)
        }.andReturn().sessionCookie()!!

        mockMvc.get("/api/v1/users/me") {
            cookie(sessionCookie)
        }.andExpect {
            status { isUnauthorized() }
            jsonPath("$.code") { value("AUTH-000") }
        }
    }
}

header { doesNotExist(HttpHeaders.SET_COOKIE) } combined with request { sessionAttributeDoesNotExist("SPRING_SECURITY_CONTEXT") } proves that NullSecurityContextRepository is actually active on /api/**.

MockMvc security test execution console passing JWT filter chain checks Figure 1. ApiSecurityTest passing statelessness, token validation, and cookie rejection checks.


Testing the session-based Admin Web chain

The Admin Web chain serves browser forms, so tests focus on CSRF enforcement, session fixation protection (changeSessionId), credential erasure in Redis, and rejecting Bearer tokens.

flowchart TD
    Req["POST /admin/login"] --> CSRF{"Valid CSRF token?"}
    CSRF -->|"No"| Forbidden["403 Forbidden"]
    CSRF -->|"Yes"| Auth{"Valid credentials?"}
    Auth -->|"No"| Fail["302 -> /admin/login?error"]
    Auth -->|"Yes"| Rotate["SessionFixation: changeSessionId()"]
    Rotate --> Store["Store AuthUser in Redis (password = null)<br/>302 -> /admin/dashboard"]
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
65
66
67
68
69
70
// 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 com.example.server.user.domain.UserRole
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.http.HttpHeaders
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 (formLogin, session)")
class AdminWebSecurityTest : IntegrationTestSupport() {

    @Test
    fun `successful login rotates session ID and erases password from Redis`() {
        val admin = createUser(roles = setOf(UserRole.ADMIN, UserRole.USER), nickname = "Admin")
        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()!!
        // Verify session fixation protection and HttpOnly flag
        assertThat(sessionCookie.value).isNotEqualTo(anonymousCookie.value)
        assertThat(sessionCookie.isHttpOnly).isTrue()

        // Verify Redis-backed principal has credentials scrubbed
        val principal = securityContextOf(sessionCookie)?.authentication?.principal
        assertThat(principal).isInstanceOf(AuthUser::class.java)
        assertThat((principal as AuthUser).id).isEqualTo(admin.id)
        assertThat(principal.password).isNull()
    }

    @Test
    fun `login without CSRF token is rejected with 403`() {
        val admin = createUser(roles = setOf(UserRole.ADMIN, UserRole.USER))
        val sessionCookie = mockMvc.get("/admin/login").andReturn().sessionCookie()!!

        mockMvc.post("/admin/login") {
            cookie(sessionCookie)
            param("username", admin.email!!)
            param("password", PASSWORD)
        }.andExpect {
            status { isForbidden() }
        }
    }

    @Test
    fun `Bearer token alone does not authenticate Admin Web`() {
        val admin = createUser(roles = setOf(UserRole.ADMIN, UserRole.USER))

        mockMvc.get("/admin/dashboard") {
            header(HttpHeaders.AUTHORIZATION, "Bearer ${accessTokenOf(admin)}")
        }.andExpect {
            status { is3xxRedirection() }
            redirectedUrl("/admin/login")
        }
    }
}

Admin Web formLogin and session security test pass console Figure 2. AdminWebSecurityTest confirming CSRF enforcement, session ID rotation, and Bearer token rejection.


Dual-chain isolation matrix and slice test balance

Running all 19 scenarios (8 API chain + 11 Admin Web chain) produced 100% line coverage and over 96% branch coverage across ApiSecurityConfig, AdminWebSecurityConfig, and ApiSecurityHandlers.

CheckAPI chain (/api/**)Admin Web chain (/admin/**)
CredentialAuthorization: Bearer <token>SESSION cookie
UnauthenticatedJSON 401 (AUTH-000, WWW-Authenticate)302 redirect to /admin/login
ForbiddenJSON 403 (AUTH-003)403 forward to /admin/403
Session policySTATELESS (no Set-Cookie)IF_REQUIRED (rotates ID on login)
CSRFDisabledEnabled (403 when missing)
Opposite credentialIgnores cookie -> 401Ignores Bearer token -> 302 login

JaCoCo coverage report for Spring Security dual filter chains Figure 3. Coverage report verifying both security filter chains and custom error handlers.

When to use @WebMvcTest instead of @SpringBootTest

Don’t write every controller test as a full @SpringBootTest—context reloads slow down CI (see Spring Test slice context caching). Split the work:

  • Controller validation and serialization (@WebMvcTest): Use SecurityMockMvcRequestPostProcessors.jwt() to test DTO validation, status codes, and JSON shapes quickly:
    1
    2
    3
    
    mockMvc.get("/api/v1/articles") {
        with(jwt().jwt { it.claim("roles", listOf("USER")) })
    }.andExpect { status { isOk() } }
    
  • Security wiring and isolation (@SpringBootTest + @AutoConfigureMockMvc): Keep a dedicated security test suite (ApiSecurityTest, AdminWebSecurityTest) that boots the real filter chains, tests @Order precedence, verifies CSRF and session rotation, and proves cross-chain isolation.

Production caveat: keep @Order and securityMatcher explicit
If the API chain omits a tight securityMatcher("/api/**") or loses its lower @Order value, it can swallow /admin/** requests and break browser logins silently. Keep both chains covered by cross-chain tests in CI so any SecurityConfig refactor fails fast.

Checklist

  • Assert header { doesNotExist(HttpHeaders.SET_COOKIE) } on stateless JWT endpoints.
  • Test both directions of cross-chain isolation (cookie against /api/**, Bearer token against /admin/**).
  • Verify session ID rotation and principal.password == null after form login.
  • Keep @WebMvcTest + jwt() for business controllers, and reserve full MockMvc integration tests for security configuration.
This post is licensed under CC BY 4.0 by the author.