Video in progress

The interceptor below validates a JWT on STOMP CONNECT. What is wrong with it, and how do you fix it?

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    StompHeaderAccessor acc = StompHeaderAccessor.wrap(message);
    String token = acc.getFirstNativeHeader("Authorization");
    if (token == null) {
        throw new AccessDeniedException("token yo'q");
    }
    acc.setUser(jwtService.toAuthentication(token));
    return message;
}

The interceptor looks for the token on every frame and rejects the frames after CONNECT because they have no header. Also, although it writes the user to the accessor, the message isn't rebuilt with the modified accessor.

📖 Answer

There are two problems.

The first is that the command isn't checked. The token is normally sent only in the CONNECT frame. SUBSCRIBE, SEND and heart-beats arrive without the header, and this code rejects all of them.

The second is that StompHeaderAccessor.wrap() creates a new accessor. Calling setUser on it doesn't affect the original message. You need to get the mutable accessor:

@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 MessageDeliveryException("token yo'q");
        }
        acc.setUser(jwtService.toAuthentication(header.substring(7)));
    }
    return message;
}

The user set in CONNECT is bound to the session, and Spring adds it itself to the following frames.

You register the interceptor in configureClientInboundChannel. If you use Spring Security, your interceptor must come before the Security interceptor, with @Order(Ordered.HIGHEST_PRECEDENCE + 99). Otherwise Security rejects a message that has no user yet.

Why not put the token in the query string? URLs end up in proxy and access logs. Sending it in a header, in the CONNECT frame, is safer.