Video in progress

Strong Middle 🌱 Spring

How do you get the current user in the service layer, and what are the traps here?

Either via SecurityContextHolder.getContext().getAuthentication(), or you grab it in the controller with @AuthenticationPrincipal and pass it to the service as a parameter. The trap is that SecurityContext lives in a ThreadLocal by default: it doesn't carry over to @Async, CompletableFuture or new threads.

📖 Answer

Getting it in the controller and passing it explicitly is the clearest way:

@PostMapping("/api/orders")
OrderDto create(@AuthenticationPrincipal Jwt jwt, @RequestBody NewOrder req) {
    return orders.create(Long.valueOf(jwt.getSubject()), req);
}

The service knows "who" from the parameter — easy to test, and it doesn't break if you move it to async.

Getting it directly inside the service:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

It works, but it creates a hidden dependency, and in these places it returns null:

  • in an @Async method (unless DelegatingSecurityContextAsyncTaskExecutor is configured);
  • inside CompletableFuture.supplyAsync(...);
  • in @Scheduled and Kafka listeners — there's no user there at all.

The fix for async:

@Bean
TaskDecorator securityContextDecorator() {
    return task -> {
        SecurityContext ctx = SecurityContextHolder.getContext();
        return () -> {
            SecurityContextHolder.setContext(ctx);
            try { task.run(); } finally { SecurityContextHolder.clearContext(); }
        };
    };
}

Don't skip the cleanup in finally, or the pooled thread moves on to its next task with someone else's permissions.