Video in progress
How do you use Spring Security to stop a user from SUBSCRIBEing to a STOMP topic they aren't allowed to?
In Spring Security 6 you enable @EnableWebSocketSecurity and write rules by destination and message type in an AuthorizationManager<Message<?>> bean. For dynamic checks (for example, is the user a room member) you write your own AuthorizationManager.
📖 Answer
Before Spring Security 6 you used AbstractSecurityWebSocketMessageBrokerConfigurer; now it's deprecated. The new way:
@Configuration
@EnableWebSocketSecurity
class WsSecurity {
@Bean
AuthorizationManager<Message<?>> messageAuth(
MessageMatcherDelegatingAuthorizationManager.Builder m) {
return m
.nullDestMatcher().authenticated()
.simpSubscribeDestMatchers("/user/queue/**").authenticated()
.simpSubscribeDestMatchers("/topic/admin/**").hasRole("ADMIN")
.simpDestMatchers("/app/**").authenticated()
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
.anyMessage().denyAll()
.build();
}
}
Don't skip the denyAll at the end. Without it a client can subscribe to anything under /topic/ and read other people's messages. This is the most common security hole.
Static rules aren't always enough. For a requirement like "a user may subscribe only to chat rooms they are a member of":
.simpSubscribeDestMatchers("/topic/room.{id}")
.access((auth, ctx) -> new AuthorizationDecision(
rooms.isMember(auth.get().getName(), ctx.getVariables().get("id"))))
isMember is called on every subscription, so it has to be fast: a cache or an indexed query.
Another trap: by default @EnableWebSocketSecurity requires a CSRF token for CONNECT. In a SPA that authenticates with a token, CONNECT gets rejected: the client receives an ERROR frame and the connection closes, and the reason (no CSRF token) shows up only in the server log.
Sign up to mark studied questions and save your progress.