Video in progress
`@PreAuthorize` in a service called from a `@MessageMapping` method fails with "An Authentication object was not found", yet the `Principal` is there. Why?
The Principal is bound to the STOMP session, but SecurityContextHolder isn't populated automatically on the clientInboundChannel thread. When @EnableWebSocketSecurity is on, Spring Security's channel interceptor sets the context for each message and method security starts to work.
📖 Answer
Two things get mixed up. The Principal argument comes from simpUser in the message headers, and Spring messaging supplies it itself. @PreAuthorize, though, looks at SecurityContextHolder, which is a ThreadLocal. The message is processed on a clientInboundChannel pool thread, where there's no filter chain like in an HTTP request, so the context is empty.
In Spring Security 6 the fix is to turn on the messaging integration:
@Configuration
@EnableWebSocketSecurity
class WsSecurityConfig {
@Bean
AuthorizationManager<Message<?>> messageAuthorizationManager(
MessageMatcherDelegatingAuthorizationManager.Builder messages) {
return messages
.nullDestMatcher().authenticated() // CONNECT, heart-beat, DISCONNECT
.simpDestMatchers("/app/**").authenticated()
.anyMessage().denyAll()
.build();
}
}
This annotation adds interceptors to the inbound channel: one puts the user from the message into SecurityContextHolder and clears it after the work, the other checks the destination rules. After that @PreAuthorize in services and the @AuthenticationPrincipal argument work too.
There are two traps here:
- By default
@EnableWebSocketSecurityexpects a CSRF token on theCONNECTframe. A SPA that sends its token in theCONNECTheader has to account for this, otherwise the connection is rejected. - If you hand the work inside the method to
@Asyncor your own executor, the context is lost again. Wrap the executor inDelegatingSecurityContextAsyncTaskExecutor, or pass the needed user data as a parameter.
If you validate the JWT in CONNECT yourself and call accessor.setUser(...), your interceptor must come before the Security interceptors; otherwise Security sees a message that has no user set yet.
Sign up to mark studied questions and save your progress.