Fixing @AuthenticationPrincipal 500 errors in Kotlin Spring Boot
Why unauthenticated requests trigger HTTP 500 with Kotlin non-null @AuthenticationPrincipal parameters, plus how to fix it with a custom ArgumentResolver.
In a Kotlin + Spring Boot app using
permitAll()with JWT authentication, an unauthenticated request hitting a non-null@AuthenticationPrincipalparameter returns500 Internal Server Errorinstead of401or403. This post traces the clash between Spring Security’s built-in resolver and Kotlin’s null-safety, compares four ways to handle it, and shows how to build a clean customHandlerMethodArgumentResolver.
Environment: Spring Boot 3.4 / Spring Security 6.4 / Kotlin 2.x (WebMVC)
The problem
When prototyping a JWT-authenticated API, it’s common to leave SecurityFilterChain open with anyRequest().permitAll() and enforce authentication at the endpoint level via @PreAuthorize or controller parameters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// config/SecurityConfig.kt
@Configuration
@EnableMethodSecurity
class SecurityConfig(
private val jwtProvider: JwtProvider,
) {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
return http
.csrf { it.disable() }
.headers { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.authorizeHttpRequests { request ->
request.anyRequest().permitAll()
}
.addFilterBefore(
JwtTokenFilter(jwtProvider),
BasicAuthenticationFilter::class.java,
)
.build()
}
}
Now call this notification endpoint without an Authorization header. You’d expect 401 Unauthorized or 403 Forbidden, yet the server returns HTTP 500 before the controller body even runs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// controller/NotificationController.kt
@RestController
@RequestMapping("/api/v1/notifications")
class NotificationController(
private val notificationService: NotificationService,
) {
@GetMapping
fun getNotifications(
@AuthenticationPrincipal authenticatedUser: AuthenticatedUser,
pageable: Pageable,
): ResponseEntity<PagedModel<NotificationResponse>> {
val page = notificationService.findAllByUserId(authenticatedUser.id, pageable)
return ResponseEntity.ok(PagedModel(page))
}
}
The stack trace shows the failure happens at Kotlin’s parameter null check right on method entry:
1
2
3
4
java.lang.NullPointerException: Parameter specified as non-null is null:
method com.example.notification.NotificationController.getNotifications, parameter authenticatedUser
at com.example.notification.NotificationController.getNotifications(NotificationController.kt)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
In Java, you’d hit an NPE later inside the method when calling authenticatedUser.getId(). Kotlin inserts Intrinsics.checkNotNullParameter() bytecode at compile time for every non-null parameter, so the moment Spring invokes the method with null, it throws NullPointerException and turns an auth failure into a 500.
Root cause: Spring Security’s resolver silently returns null
The bug happens in the handoff between SecurityFilterChain and Spring MVC’s HandlerMethodArgumentResolver pipeline:
flowchart TD
REQ["Unauthenticated request (no JWT)"] --> ANON["AnonymousAuthenticationFilter (principal='anonymousUser')"]
ANON -->|"passes permitAll"| RES["AuthenticationPrincipalArgumentResolver"]
RES -->|"returns null on type mismatch"| INV["Kotlin checkNotNullParameter()"]
INV -->|"NullPointerException"| ERR["HTTP 500 response"]
- Anonymous authentication: Without a JWT header,
JwtTokenFilterleavesSecurityContextHolderempty.AnonymousAuthenticationFilterruns next and populates anAnonymousAuthenticationTokenwhoseprincipalis the String"anonymousUser". - Filter authorization passes: Because
anyRequest().permitAll()allows anonymous requests,AuthorizationFilterforwards the request straight toDispatcherServlet. - Built-in resolver returns
null: Spring Security’s auto-registeredorg.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolverreadsauthentication.principaland checks whether it’s assignable to the parameter type (AuthenticatedUser)."anonymousUser"(String) isn’t assignable toAuthenticatedUser, so by default the resolver silently returnsnullinstead of throwing. - Kotlin non-null check fails:
InvocableHandlerMethodpasses thatnullintogetNotifications(...). Kotlin’s generatedcheckNotNullParameter()immediately throwsNullPointerException, producing HTTP500.
Comparing the four ways to fix it
Choosing the right fix comes down to which layer should own authentication enforcement:
| Approach | How it works | Status code control | Best fit |
|---|---|---|---|
1. Explicit auth rules (authenticated() / @PreAuthorize) | Blocks unauthenticated requests in the filter chain or AOP before the controller | Consistent 401 via AuthenticationEntryPoint | Production default (defense in depth) |
2. Nullable parameter (AuthenticatedUser?) | Accepts null and branches inside the handler | Custom per-endpoint behavior | Public endpoints that work for both guests and signed-in users |
3. @AuthenticationPrincipal(errorOnInvalidType = true) | Throws ClassCastException on type mismatch | Map to 401 in @RestControllerAdvice | Quick distinction for anonymous mismatch (still doesn’t catch principal == null) |
4. Custom ArgumentResolver + dedicated annotation | Throws a domain UnauthorizedException during argument binding | Unified 401 via global exception handler | permitAll() setups or explicit separation of required vs. optional user parameters |
When not to use a custom
ArgumentResolverIf your goal is simply to block unauthenticated access to protected routes, enforce it in
SecurityFilterChainor with@PreAuthorize("isAuthenticated()"). Deferring authentication checks to MVC argument binding leaves a security gap: any protected endpoint whose controller forgets to declare the user parameter becomes publicly accessible. For separating public and protected routes cleanly, use the whitelist pattern I covered in configuring multiple Spring Security filter chains.
Building and registering a custom ArgumentResolver
If you want argument binding itself to throw a clean 401 Unauthorized on unauthenticated calls, you can implement HandlerMethodArgumentResolver. There is one subtle trap to avoid first.
Watch out: overriding @AuthenticationPrincipal causes ordering conflicts
Spring Security’s WebMvcSecurityConfiguration registers its built-in AuthenticationPrincipalArgumentResolver through WebMvcConfigurer.addArgumentResolvers()—the exact same hook your custom config uses. If your resolver also checks for @AuthenticationPrincipal in supportsParameter(), bean registration order can put Spring Security’s resolver first, leaving you with the same null return value.
The safest fix is to introduce a dedicated annotation like @CurrentUser so the two resolvers never compete:
1
2
3
4
// security/CurrentUser.kt
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class CurrentUser
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
// security/CurrentUserArgumentResolver.kt
@Component
class CurrentUserArgumentResolver : HandlerMethodArgumentResolver {
override fun supportsParameter(parameter: MethodParameter): Boolean {
return parameter.hasParameterAnnotation(CurrentUser::class.java) &&
AuthenticatedUser::class.java.isAssignableFrom(parameter.parameterType)
}
override fun resolveArgument(
parameter: MethodParameter,
mavContainer: ModelAndViewContainer?,
webRequest: NativeWebRequest,
binderFactory: WebDataBinderFactory?,
): Any? {
val auth = SecurityContextHolder.getContext().authentication
val principal = auth?.principal as? AuthenticatedUser
if (principal == null) {
if (parameter.isOptional || isKotlinNullable(parameter)) {
return null
}
throw UnauthorizedException("Authentication is required.")
}
return principal
}
private fun isKotlinNullable(parameter: MethodParameter): Boolean {
val kParam = parameter.method?.kotlinFunction?.valueParameters
?.getOrNull(parameter.parameterIndex)
return kParam?.type?.isMarkedNullable == true
}
}
This resolver handles both required and optional authentication cleanly:
- Declaring
@CurrentUser user: AuthenticatedUser(non-null) immediately throwsUnauthorizedExceptionwhenever authentication is missing or anonymous. - Declaring
@CurrentUser user: AuthenticatedUser?(nullable) returnsnullwithout throwing, so public endpoints can reuse the exact same annotation.
Registering with WebMvcConfigurer and mapping to 401
Annotating the resolver with @Component alone doesn’t plug it into Spring MVC—you must register it in WebMvcConfigurer.addArgumentResolvers():
1
2
3
4
5
6
7
8
9
// config/WebMvcConfig.kt
@Configuration
class WebMvcConfig(
private val currentUserArgumentResolver: CurrentUserArgumentResolver,
) : WebMvcConfigurer {
override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) {
resolvers.add(currentUserArgumentResolver)
}
}
Next, map UnauthorizedException to a 401 Unauthorized ProblemDetail response in your global exception handler and switch the controller parameter to @CurrentUser:
1
2
3
4
5
6
7
8
9
10
11
// exception/GlobalExceptionHandler.kt
class UnauthorizedException(message: String) : RuntimeException(message)
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(UnauthorizedException::class)
fun handleUnauthorized(ex: UnauthorizedException): ResponseEntity<ProblemDetail> {
val detail = ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED, ex.message ?: "Unauthorized")
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(detail)
}
}
1
2
3
4
5
6
7
8
9
// controller/NotificationController.kt
@GetMapping
fun getNotifications(
@CurrentUser authenticatedUser: AuthenticatedUser,
pageable: Pageable,
): ResponseEntity<PagedModel<NotificationResponse>> {
val page = notificationService.findAllByUserId(authenticatedUser.id, pageable)
return ResponseEntity.ok(PagedModel(page))
}
Verification
Call the endpoint without a token using curl and confirm it returns a 401 Unauthorized ProblemDetail payload instead of 500:
1
curl -i http://localhost:8080/api/v1/notifications
1
2
3
4
5
6
7
8
9
10
HTTP/1.1 401 Unauthorized
Content-Type: application/problem+json
{
"type": "about:blank",
"title": "Unauthorized",
"status": 401,
"detail": "Authentication is required.",
"instance": "/api/v1/notifications"
}
Lock the behavior in with a MockMvc regression test covering unauthenticated requests (for details on wiring Spring Security test contexts, see my Spring Security MockMvc testing guide):
1
2
3
4
5
6
7
8
9
// controller/NotificationControllerTest.kt
@Test
fun `returns 401 instead of 500 when calling notifications API without a token`() {
mockMvc.get("/api/v1/notifications")
.andExpect {
status { isUnauthorized() }
jsonPath("$.detail") { value("Authentication is required.") }
}
}
Production caveats and checklist
Kotlin’s compile-time null-safety catches real bugs, but at the boundary with Java framework resolvers that return null, it can mask an authentication failure as a 500 server error. Keep these four checks in mind:
- Default to deny in production: Avoid
anyRequest().permitAll()in productionSecurityFilterChainconfigs—whitelist public paths explicitly and default toanyRequest().authenticated(). - Avoid resolver ordering collisions: Use a dedicated annotation like
@CurrentUserinstead of trying to intercept Spring Security’s@AuthenticationPrincipal. - Respect Kotlin nullability: Check
isMarkedNullableinside your resolver soAuthenticatedUser?continues working on mixed guest/authenticated endpoints. - Keep a
401regression test: Add at least one unauthenticatedMockMvctest per protected controller to ensure missing tokens return401, never500.