Configuring JWT authentication with Spring Resource Server
Configure Spring Security's Resource Server for stateless JWT authentication, separate access and refresh decoders, and consistent JSON errors.
I replaced a custom JWT filter with Spring Security’s OAuth 2.0 Resource Server. The standard filter chain handles Bearer authentication, while separate decoders enforce the intended use of access and refresh tokens.
The examples use Spring Boot 3.5, Kotlin 1.9, Java 21, and spring-boot-starter-oauth2-resource-server.
Replacing the custom JWT filter
With OncePerRequestFilter and jjwt, my application would own Bearer parsing, signature checks, the security context, and exception handling. Returning early after catching a validation error can leave the response at its default status. Writing the response directly can also give one path a different error format.
| Responsibility | Custom JWT filter | Resource Server |
|---|---|---|
| Extract the credential | Parse the authorization header | Resolve it through a BearerTokenResolver |
| Validate the credential | Compose checks in application code | Use NimbusJwtDecoder and the validator chain |
| Report authentication failure | Set status and body explicitly | Delegate to AuthenticationEntryPoint |
| Establish the principal | Build an Authentication | Convert a verified Jwt into JwtAuthenticationToken |
I adopted the starter because the service uses stateless authentication and the standard Bearer header. An application that keeps credentials in cookies or reloads authorization on every request will still need to design those policies explicitly. Spring Security Resource Server JWT support
1
2
3
4
5
6
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-validation")
}
Validating configuration before issuing tokens
An HS256 signing key must contain at least 32 bytes. Discovering a short key on the first login turns deployment configuration into a runtime error. I used @Validated on JwtProperties with field-level constraints for the key, issuer, and lifetimes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/main/kotlin/org/project/portfolio/auth/JwtProperties.kt
@Validated
@ConfigurationProperties(prefix = "jwt")
data class JwtProperties(
@field:NotBlank(message = "The JWT secret must not be blank.")
@field:Size(min = 32, message = "The JWT secret must contain at least 32 characters for HS256.")
val secret: String,
@field:NotBlank(message = "The JWT issuer must not be blank.")
val issuer: String,
@field:Positive(message = "accessExpiry must be positive.")
val accessExpiry: Long = 3600,
@field:Positive(message = "refreshExpiry must be positive.")
val refreshExpiry: Long = 604800,
)
In Kotlin 1.9, @field: puts these constraints on the backing fields so bean validation finds them. The sample uses @Size(min = 32) on a string. That is a character check. When storing a Base64-encoded key, validate the decoded bytes before building the encoder. Keep the signing key in secret configuration and use random key material.
JwtProvider sets token_type on both JWT kinds. It adds roles only to the access token, because the refresh endpoint uses the refresh token to issue new credentials and does not derive authorities from it.
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
// src/main/kotlin/org/project/portfolio/auth/JwtProvider.kt
@Component
class JwtProvider(
private val jwtProperties: JwtProperties,
private val jwtEncoder: JwtEncoder,
@Qualifier("refreshJwtDecoder")
private val refreshJwtDecoder: JwtDecoder,
) {
fun createAccessToken(
email: String,
roles: Set<UserRole>,
jit: String = UUID.randomUUID().toString(),
issuedAt: Instant = Instant.now(),
duration: Long = jwtProperties.accessExpiry,
): String {
val claims = defaultClaims(email, jit, issuedAt, duration, TokenType.ACCESS_TOKEN)
.claim("roles", roles.map { it.authority })
.build()
return encode(claims)
}
fun createRefreshToken(
email: String,
jit: String,
issuedAt: Instant = Instant.now(),
duration: Long = jwtProperties.refreshExpiry,
): String {
val claims = defaultClaims(email, jit, issuedAt, duration, TokenType.REFRESH_TOKEN).build()
return encode(claims)
}
fun decodeRefreshToken(token: String): RefreshToken {
return try {
val jwt = refreshJwtDecoder.decode(token)
RefreshToken(email = jwt.subject, jit = jwt.id)
} catch (e: JwtException) {
throw UnauthorizedException("Invalid token")
}
}
private fun defaultClaims(
subject: String,
jit: String,
issuedAt: Instant,
duration: Long,
tokenType: TokenType,
): JwtClaimsSet.Builder = JwtClaimsSet.builder()
.id(jit)
.issuer(jwtProperties.issuer)
.subject(subject)
.issuedAt(issuedAt)
.notBefore(issuedAt)
.expiresAt(issuedAt.plusSeconds(duration))
.claim("token_type", tokenType.name)
private fun encode(claims: JwtClaimsSet): String {
val header = JwsHeader.with(MacAlgorithm.HS256).type("JWT").build()
return jwtEncoder.encode(JwtEncoderParameters.from(header, claims)).tokenValue
}
enum class TokenType { ACCESS_TOKEN, REFRESH_TOKEN }
}
Enforcing the token’s intended purpose
Both JWT kinds share an issuer and signing key in this project. The access decoder therefore treats a valid signature as one requirement. It also rejects a refresh token whose token_type claim does not match ACCESS_TOKEN. The separately qualified refresh decoder requires REFRESH_TOKEN.
flowchart TD
A["Bearer request"] --> B["BearerTokenAuthenticationFilter"]
B --> C["Validate JWT claims"]
C --> D["Check access token type"]
D -->|"Invalid"| E["401 JSON ErrorResponse"]
D -->|"Valid"| F["Convert JWT roles"]
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
// src/main/kotlin/org/project/portfolio/config/JwtConfig.kt
@Configuration
@EnableConfigurationProperties(JwtProperties::class)
class JwtConfig(
private val jwtProperties: JwtProperties,
) {
private val secretKey: SecretKey = SecretKeySpec(
jwtProperties.secret.toByteArray(Charsets.UTF_8),
"HmacSHA256",
)
@Bean
fun jwtEncoder(): JwtEncoder = NimbusJwtEncoder(ImmutableSecret<SecurityContext>(secretKey))
@Bean
@Primary
fun jwtDecoder(): JwtDecoder = buildDecoder(JwtProvider.TokenType.ACCESS_TOKEN)
@Bean
@Qualifier("refreshJwtDecoder")
fun refreshJwtDecoder(): JwtDecoder = buildDecoder(JwtProvider.TokenType.REFRESH_TOKEN)
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
val authoritiesConverter = JwtGrantedAuthoritiesConverter().apply {
setAuthoritiesClaimName("roles")
setAuthorityPrefix("")
}
return JwtAuthenticationConverter().apply {
setJwtGrantedAuthoritiesConverter(authoritiesConverter)
setPrincipalClaimName("sub")
}
}
private fun buildDecoder(expectedType: JwtProvider.TokenType): JwtDecoder {
val decoder = NimbusJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS256)
.build()
val defaultValidator = JwtValidators.createDefaultWithIssuer(jwtProperties.issuer)
val tokenTypeValidator = OAuth2TokenValidator<Jwt> { jwt ->
if (jwt.getClaimAsString("token_type") == expectedType.name) {
OAuth2TokenValidatorResult.success()
} else {
OAuth2TokenValidatorResult.failure(
OAuth2Error("invalid_token", "Expected ${expectedType.name} token", null),
)
}
}
decoder.setJwtValidator(DelegatingOAuth2TokenValidator(defaultValidator, tokenTypeValidator))
return decoder
}
}
The primary decoder is the access decoder used by the Resource Server. The refresh flow requests @Qualifier("refreshJwtDecoder"). DelegatingOAuth2TokenValidator combines the issuer and timestamp checks with the purpose check, which keeps allowed token kind explicit even when the claim sets overlap. See the account API for the Redis-backed refresh rotation that follows decoding.
I stored ROLE_USER and ROLE_ADMIN directly in the roles claim. setAuthoritiesClaimName("roles") reads that claim and setAuthorityPrefix("") retains the role strings. setPrincipalClaimName("sub") exposes the email as authentication.name. Leaving the scope prefix active would map an existing role to a different authority and make role checks fail.
Returning consistent JSON errors
The security configuration permits the public endpoints and requires authentication for the remaining requests. A valid identity only establishes the principal. Method security decides whether that principal can perform the requested operation.
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
// src/main/kotlin/org/project/portfolio/config/SecurityConfig.kt
@Configuration
@EnableMethodSecurity
class SecurityConfig(
private val jwtAuthenticationConverter: JwtAuthenticationConverter,
private val objectMapper: ObjectMapper,
) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
return http
.csrf { it.disable() }
.headers { headers -> headers.frameOptions { it.sameOrigin() } }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.authorizeHttpRequests { auth ->
auth
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers(
"/api/v1/auth/login",
"/api/v1/auth/register",
"/api/v1/auth/register/email",
"/api/v1/auth/refresh",
"/api/v1/auth/logout",
).permitAll()
.requestMatchers(
HttpMethod.GET,
"/api/v1/articles",
"/api/v1/articles/*",
"/api/v1/articles/*/comments",
"/api/v1/users/*",
).permitAll()
.requestMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**", "/actuator/health")
.permitAll()
.anyRequest().authenticated()
}
.oauth2ResourceServer { oauth2 ->
oauth2.jwt { it.jwtAuthenticationConverter(jwtAuthenticationConverter) }
oauth2.authenticationEntryPoint(jsonAuthenticationEntryPoint())
oauth2.accessDeniedHandler(jsonAccessDeniedHandler())
}
.exceptionHandling { exceptions ->
exceptions.authenticationEntryPoint(jsonAuthenticationEntryPoint())
exceptions.accessDeniedHandler(jsonAccessDeniedHandler())
}
.addFilterBefore(LoggingFilter(), UsernamePasswordAuthenticationFilter::class.java)
.build()
}
private fun jsonAuthenticationEntryPoint(): AuthenticationEntryPoint =
AuthenticationEntryPoint { _, response, _ ->
response.status = HttpServletResponse.SC_UNAUTHORIZED
response.contentType = MediaType.APPLICATION_JSON_VALUE
objectMapper.writeValue(
response.outputStream,
ErrorResponse(code = "UNAUTHORIZED", message = "Authentication is required."),
)
}
private fun jsonAccessDeniedHandler(): AccessDeniedHandler =
AccessDeniedHandler { _, response, _ ->
response.status = HttpServletResponse.SC_FORBIDDEN
response.contentType = MediaType.APPLICATION_JSON_VALUE
objectMapper.writeValue(
response.outputStream,
ErrorResponse(code = "FORBIDDEN", message = "Access is denied."),
)
}
}
ErrorResponse includes a timestamp and reads the trace identifier from MDC. I wired the authentication entry point and access-denied handler into the filter configuration so clients can parse the same JSON shape on failures.
1
2
3
4
5
6
7
8
// src/main/kotlin/org/project/portfolio/common/presentation/response/ErrorResponse.kt
data class ErrorResponse(
val code: String,
val message: String?,
val properties: Map<String, Any?> = mapOf(),
val traceId: String? = MDC.get(LoggingFilter.TRACE_ID),
val timestamp: Instant = Instant.now(),
)
Several parts of Spring can see the failure first. BearerTokenAuthenticationFilter handles a malformed or invalid Bearer credential. ExceptionTranslationFilter helps route authentication or authorization exceptions for requests that reach the rest of the chain. A controller-side AccessDeniedException from @PreAuthorize can also reach @RestControllerAdvice, so the advice returns the same 403 body.
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/main/kotlin/org/project/portfolio/common/presentation/GlobalExceptionHandler.kt (excerpt)
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(UnauthorizedException::class)
private fun handleUnauthorizedException(e: UnauthorizedException): ResponseEntity<ErrorResponse> =
ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(ErrorResponse(code = e.code, message = e.message, properties = e.properties))
@ExceptionHandler(AccessDeniedException::class)
private fun handleAccessDeniedException(): ResponseEntity<ErrorResponse> =
ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ErrorResponse(code = "FORBIDDEN", message = "Access is denied."))
}
Checking principal and role behavior
After authentication, the controller can take @AuthenticationPrincipal jwt: Jwt and read jwt.subject. @EnableMethodSecurity activates the authorization rules. I use @PreAuthorize to allow editing or deleting an article to its author or an administrator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// UserController.kt & ArticleController.kt (excerpt)
@GetMapping("/user")
@PreAuthorize("isAuthenticated()")
fun getUserInfo(@AuthenticationPrincipal jwt: Jwt): ResponseEntity<UserResponse> =
ResponseEntity.ok(UserResponse.from(userQueryService.getUser(email = jwt.subject)))
@PatchMapping("/{articleId}", consumes = ["multipart/form-data"])
@PreAuthorize("isAuthenticated() and (hasRole('ROLE_ADMIN') or @articleValidator.isEditable(#articleId, authentication.name))")
fun updateArticle(
@AuthenticationPrincipal jwt: Jwt,
@PathVariable articleId: Long,
@Valid @ModelAttribute articleUpdateForm: ArticleUpdateForm,
): ResponseEntity<ArticleResponse> =
ResponseEntity.ok(articleCommandService.updateArticle(articleId, articleUpdateForm))
A malformed token can result in a
401before a downstream logging filter runs. Register the request trace filter early enough to put the identifier in MDC for failures emitted by the security chain.
- Check that a protected endpoint gives an unauthenticated caller a
401and gives an authenticated non-owner a403where required. - Verify that the active access decoder rejects a refresh token and that the refresh decoder rejects an access token.
- Inspect mapped authorities for an admin token and confirm they retain the
ROLE_prefix exactly once. - Compare the JSON error body and trace ID across filter-chain failures and method-authorization failures.
