Video in progress

You need to send a private message to a user who isn't logged in (anonymous), for example because their cart was updated. There's no Principal and convertAndSendToUser doesn't work. What do you do?

During the handshake you assign a Principal to every anonymous connection yourself: extend DefaultHandshakeHandler, override determineUser, and return a Principal with a random ID or one taken from a cookie. After that the /user/queue/... mechanism works as usual.

📖 Answer

User destinations rely entirely on Principal.getName(). Even with Spring Security, for an anonymous user request.getUserPrincipal() returns null: AnonymousAuthenticationToken doesn't surface here. As a result the session has no name, convertAndSendToUser can't find it, and the message silently disappears.

The fix:

class AnonymousAwareHandshakeHandler extends DefaultHandshakeHandler {
    @Override
    protected Principal determineUser(ServerHttpRequest request,
                                      WebSocketHandler handler,
                                      Map<String, Object> attributes) {
        Principal user = super.determineUser(request, handler, attributes);
        if (user != null) {
            return user;
        }
        String guestId = (String) attributes.getOrDefault("guestId", UUID.randomUUID().toString());
        return () -> "guest:" + guestId;
    }
}
registry.addEndpoint("/ws")
        .setHandshakeHandler(new AnonymousAwareHandshakeHandler())
        .addInterceptors(new GuestCookieInterceptor()); // puts the guestId from the cookie into attributes

Now in the cart service the server does convertAndSendToUser("guest:" + guestId, "/queue/cart", dto).

Why is it better to take guestId from the cookie? A random UUID is new on every reconnect, and the backend wouldn't know which connection this cart belongs to. If the cart is already linked to the ID in the cookie, using that same ID makes sense.

Be careful: the guest: prefix isn't arbitrary. It must not collide with a real username. And such a "guest" principal must never be a trusted identifier in an authorization decision; it's only a delivery address.