Video in progress

How do you validate a JWT in the STOMP CONNECT frame in Spring and bind the user to the session?

You add a ChannelInterceptor to the clientInboundChannel: on the CONNECT command it takes the token from the header, validates it and calls accessor.setUser(authentication). After that every message in that session carries a Principal.

📖 Answer

@Configuration
@EnableWebSocketMessageBroker
public class StompAuthConfig implements WebSocketMessageBrokerConfigurer {

    private final JwtDecoder jwtDecoder;
    private final JwtAuthenticationConverter converter = new JwtAuthenticationConverter();

    public StompAuthConfig(JwtDecoder jwtDecoder) { this.jwtDecoder = jwtDecoder; }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor acc =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (acc != null && StompCommand.CONNECT.equals(acc.getCommand())) {
                    String header = acc.getFirstNativeHeader("Authorization");
                    if (header == null || !header.startsWith("Bearer ")) {
                        throw new MessagingException("token yo'q");
                    }
                    Jwt jwt = jwtDecoder.decode(header.substring(7));
                    acc.setUser(converter.convert(jwt));
                }
                return message;
            }
        });
    }
}

The important parts:

  • An accessor obtained with getAccessor(message, ...) is mutable, so setUser is written onto that very message. If you create a new accessor with StompHeaderAccessor.wrap(message), the change is lost. That's the classic mistake.
  • If an exception is thrown, the client gets an ERROR frame and the connection is closed.
  • If you use Spring Security, this interceptor must come before the security interceptors. For ordering, make it a separate configuration class with @Order(Ordered.HIGHEST_PRECEDENCE + 99).

Then you grant permissions at the destination level through @EnableWebSocketSecurity and AuthorizationManager<Message<?>>: for example, /app/admin.** for ADMIN only.