Give STOMP sessions a principal so /user/queue/errors is delivered
ChatWebSocketController reports send errors with convertAndSendToUser, but CONNECT never set a user on the session, so those messages had no recipient. The interceptor now sets a principal named after the user id on the message's own accessor and allows subscriptions to /user/queue/** (resolved per session by Spring, so it cannot reach another user's queue). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ package com.krylov.refound.util;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import com.krylov.refound.service.ChatService;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -13,6 +14,9 @@ import org.springframework.messaging.MessagingException;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.messaging.support.ChannelInterceptor;
|
||||
import org.springframework.messaging.support.MessageHeaderAccessor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@@ -28,6 +32,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
private static final Pattern UNREAD_TOPIC = Pattern.compile("^/topic/user/(\\d+)/unread$");
|
||||
/** /user/{userId}/queue/** — личная очередь одного пользователя */
|
||||
private static final Pattern USER_QUEUE = Pattern.compile("^/user/[^/]+/queue/.+$");
|
||||
/**
|
||||
* /user/queue/** — личная очередь текущей сессии. Spring сам подставляет в неё
|
||||
* Principal сессии, поэтому чужую очередь так получить нельзя. Именно сюда
|
||||
* доходят сообщения convertAndSendToUser (например, /user/queue/errors).
|
||||
*/
|
||||
private static final Pattern OWN_USER_QUEUE = Pattern.compile("^/user/queue/.+$");
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserService userService;
|
||||
@@ -45,7 +55,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
|
||||
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
|
||||
// Изменяемый accessor самого сообщения: setUser на копии из wrap() не доходил бы
|
||||
// до STOMP-сессии
|
||||
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
|
||||
if (accessor == null) {
|
||||
accessor = StompHeaderAccessor.wrap(message);
|
||||
}
|
||||
|
||||
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
|
||||
handleConnect(accessor);
|
||||
@@ -81,6 +96,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
|
||||
accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
|
||||
accessor.getSessionAttributes().put(ROLE_ATTR, role);
|
||||
// Principal с именем = userId: без него convertAndSendToUser(userId, ...) никого
|
||||
// не находил, и ошибки отправки сообщений (/queue/errors) терялись
|
||||
accessor.setUser(new UsernamePasswordAuthenticationToken(userId.toString(), null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_" + role))));
|
||||
|
||||
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message
|
||||
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
|
||||
@@ -123,6 +142,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
return;
|
||||
}
|
||||
|
||||
if (OWN_USER_QUEUE.matcher(destination).matches()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (USER_QUEUE.matcher(destination).matches()) {
|
||||
String[] parts = destination.split("/");
|
||||
if (parts.length < 3 || !userId.toString().equals(parts[2])) {
|
||||
|
||||
Reference in New Issue
Block a user