在我的 spring-boot
我的申请表 spring-security
以及 spring-websocket
. 下面是我的websocket配置。
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport
implements WebSocketMessageBrokerConfigurer {
@Value( "${rabbitmq.host}" )
private String rabbitmqHost;
@Value( "${rabbitmq.stomp.port}" )
private int rabbitmqStompPort;
@Value( "${rabbitmq.username}" )
private String rabbitmqUserName;
@Value( "${rabbitmq.password}" )
private String rabbitmqPassword;
@Override
public void configureMessageBroker( MessageBrokerRegistry registry )
{
registry.enableStompBrokerRelay("/topic", "/queue").setRelayHost(rabbitmqHost).setRelayPort(rabbitmqStompPort)
.setSystemLogin(rabbitmqUserName).setSystemPasscode(rabbitmqPassword);
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints( StompEndpointRegistry stompEndpointRegistry )
{
stompEndpointRegistry.addEndpoint("/ws")
.setAllowedOrigins("*")
.withSockJS();
}
}
而且,
public class CustomSubProtocolWebSocketHandler extends SubProtocolWebSocketHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomSubProtocolWebSocketHandler.class);
@Autowired
private UserCommons userCommons;
CustomSubProtocolWebSocketHandler(MessageChannel clientInboundChannel,
SubscribableChannel clientOutboundChannel) {
super(clientInboundChannel, clientOutboundChannel);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOGGER.info("************************************************************************************************************************New webSocket connection was established: {}", session);
String token = session.getUri().getQuery().replace("token=", "");
try
{
String user = Jwts.parser().setSigningKey(TokenConstant.SECRET)
.parseClaimsJws(token.replace(TokenConstant.TOKEN_PREFIX, "")).getBody().getSubject();
Optional<UserModel> userModelOptional = userCommons.getUserByEmail(user);
if( !userModelOptional.isPresent() )
{
LOGGER.error(
"************************************************************************************************************************Invalid token is passed with web socket request");
throw new DataException(GeneralConstants.EXCEPTION, "Invalid user", HttpStatus.BAD_REQUEST);
}
}
catch( Exception e )
{
LOGGER.error(GeneralConstants.ERROR, e);
}
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
LOGGER.error("************************************************************************************************************************webSocket connection was closed");
LOGGER.error("Reason for closure {} Session: {} ", closeStatus.getReason(),session.getId() );
super.afterConnectionClosed(session, closeStatus);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
LOGGER.error("************************************************************************************************************************Connection closed unexpectedly");
LOGGER.error(GeneralConstants.ERROR, exception);
super.handleTransportError(session, exception);
}
}
要在建立连接时添加安全层,我接受连接url中的令牌。因此客户端应用程序将连接到 /ws?token=*****
.
但是为了将消息发送给特定的用户,我正在使用用户id构造订阅url /topic/noti.23
从服务器端我将消息发送到 /topic/noti.23
.
public void sendMessagesToTheDestination( WebSocketNotificationResponseBean webSocketNotificationResponseBean,
List<String> paths )
{
try
{
for( String path : paths )
{
LOGGER.info("Sending message to path: {}", path);
messagingTemplate.convertAndSend(path, webSocketNotificationResponseBean);
LOGGER.info("Sent message to path: {}", path);
}
}
catch( Exception e )
{
LOGGER.error("Error while sending web socket notification {}", e);
}
}
}
哪里 path
是 /topic/noti.<user_id>
.
上述实施正在发挥作用。
现在的问题是,任何拥有有效令牌的用户都可以连接到websocket,然后从浏览器控制台手动订阅任何url。例如,用户id为23的用户可以进入浏览器控制台并添加sockjs cdn,并且可以订阅 /topic/noti.56
并开始接收用户id为56的用户的消息。
如何在这里添加安全层?
我试过用 convertAndSendToUser
但是没有理解会话部分,即服务器如何理解会话以及我应该如何从客户端订阅。
谢谢您
1条答案
按热度按时间9q78igpj1#
您不需要动态地构造目的地。你可以订阅一个像“/user/queue/wishes”这样的目的地,仍然可以发送私人消息。