Spring › Feature

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.

Fixing @AuthenticationPrincipal 500 errors in Kotlin Spring Boot

In a Kotlin + Spring Boot app using permitAll() with JWT authentication, an unauthenticated request hitting a non-null @AuthenticationPrincipal parameter returns 500 Internal Server Error instead of 401 or 403. 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 custom HandlerMethodArgumentResolver.

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"]
  1. Anonymous authentication: Without a JWT header, JwtTokenFilter leaves SecurityContextHolder empty. AnonymousAuthenticationFilter runs next and populates an AnonymousAuthenticationToken whose principal is the String "anonymousUser".
  2. Filter authorization passes: Because anyRequest().permitAll() allows anonymous requests, AuthorizationFilter forwards the request straight to DispatcherServlet.
  3. Built-in resolver returns null: Spring Security’s auto-registered org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver reads authentication.principal and checks whether it’s assignable to the parameter type (AuthenticatedUser). "anonymousUser" (String) isn’t assignable to AuthenticatedUser, so by default the resolver silently returns null instead of throwing.
  4. Kotlin non-null check fails: InvocableHandlerMethod passes that null into getNotifications(...). Kotlin’s generated checkNotNullParameter() immediately throws NullPointerException, producing HTTP 500.

Comparing the four ways to fix it

Choosing the right fix comes down to which layer should own authentication enforcement:

ApproachHow it worksStatus code controlBest fit
1. Explicit auth rules (authenticated() / @PreAuthorize)Blocks unauthenticated requests in the filter chain or AOP before the controllerConsistent 401 via AuthenticationEntryPointProduction default (defense in depth)
2. Nullable parameter (AuthenticatedUser?)Accepts null and branches inside the handlerCustom per-endpoint behaviorPublic endpoints that work for both guests and signed-in users
3. @AuthenticationPrincipal(errorOnInvalidType = true)Throws ClassCastException on type mismatchMap to 401 in @RestControllerAdviceQuick distinction for anonymous mismatch (still doesn’t catch principal == null)
4. Custom ArgumentResolver + dedicated annotationThrows a domain UnauthorizedException during argument bindingUnified 401 via global exception handlerpermitAll() setups or explicit separation of required vs. optional user parameters

When not to use a custom ArgumentResolver

If your goal is simply to block unauthenticated access to protected routes, enforce it in SecurityFilterChain or 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 throws UnauthorizedException whenever authentication is missing or anonymous.
  • Declaring @CurrentUser user: AuthenticatedUser? (nullable) returns null without 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 production SecurityFilterChain configs—whitelist public paths explicitly and default to anyRequest().authenticated().
  • Avoid resolver ordering collisions: Use a dedicated annotation like @CurrentUser instead of trying to intercept Spring Security’s @AuthenticationPrincipal.
  • Respect Kotlin nullability: Check isMarkedNullable inside your resolver so AuthenticatedUser? continues working on mixed guest/authenticated endpoints.
  • Keep a 401 regression test: Add at least one unauthenticated MockMvc test per protected controller to ensure missing tokens return 401, never 500.
This post is licensed under CC BY 4.0 by the author.