0Pricing
WebSockets & Real-Time Systems with Spring · Урок

Защита конечных точек STOMP с помощью Spring Security

Узнайте, как выполнять аутентификацию и авторизацию обмена сообщениями STOMP в Spring, защищая рукопожатие, адресаты и сообщения для отдельных пользователей от несанкционированного доступа.

«Защита конечных точек STOMP с помощью Spring Security» — бесплатный урок WebSockets & Real-Time Systems with Spring на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebSockets & Real-Time Systems with Spring, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebSockets & Real-Time Systems with Spring содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Secure STOMP?

An open STOMP endpoint lets anyone subscribe to and publish on any destination. Securing STOMP ensures only authenticated users connect and only authorized users access specific destinations.

This lesson layers Spring Security onto STOMP messaging.

Two Layers of Security

STOMP security operates at two levels:

  • Handshake: authenticate the user when the WebSocket connection opens
  • Message: authorize each SUBSCRIBE and SEND to a destination

Both layers are needed for real protection.

Authenticating the Handshake

The connection should carry the user's identity. With session-based auth, Spring Security propagates the HTTP session principal into the WebSocket session automatically.

Token Auth on CONNECT

For token-based auth, read the token from the STOMP CONNECT frame headers using a ChannelInterceptor and set the authenticated principal on the message.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    StompHeaderAccessor acc = StompHeaderAccessor.wrap(message);
    if (StompCommand.CONNECT.equals(acc.getCommand())) {
        String token = acc.getFirstNativeHeader('Authorization');
        Authentication user = tokenService.validate(token);
        acc.setUser(user);
    }
    return message;
}

Authorizing Destinations

Spring provides AbstractSecurityWebSocketMessageBrokerConfigurer to define which roles may access which destinations, similar to HTTP security rules.

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        .simpDestMatchers('/app/admin/**').hasRole('ADMIN')
        .simpSubscribeDestMatchers('/topic/public').permitAll()
        .anyMessage().authenticated();
}

Per-User Destinations

The /user/** prefix routes messages to a single user's private queue. Spring resolves these against the authenticated principal, so users only receive their own messages.

// Server side: send to a specific user
messagingTemplate.convertAndSendToUser(
    username, '/queue/notifications', payload);

CSRF Considerations

The WebSocket handshake is an HTTP request and can be subject to CSRF. Validate origins and, where applicable, require a CSRF token so attackers cannot open connections from malicious pages.

Restricting Origins

Always lock down allowed origins for the STOMP endpoint. An open origin policy lets any website connect on behalf of a logged-in user.

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint('/ws')
            .setAllowedOrigins('https://app.example.com')
            .withSockJS();
}

Validating Message Payloads

Authentication is not enough; validate the content of every message. Reject oversized payloads, unexpected fields, and malformed data to prevent injection and resource exhaustion.

  • Enforce size limits
  • Validate against a schema
  • Reject unknown destinations

Logging Security Events

Log failed connections, denied subscriptions, and authorization failures. These events feed monitoring and help detect abuse or probing of your messaging layer.

Defense in Depth

Combine handshake auth, destination authorization, origin restriction, and payload validation. No single control is sufficient; layered controls keep your real-time messaging secure even if one fails.

Quick Check

Test your understanding of STOMP security.

Recap

You learned to secure STOMP at two layers: authenticate the handshake (session or token), then authorize destinations with Spring Security rules. Per-user destinations, origin restrictions, payload validation, and event logging together provide defense in depth for real-time messaging.

Часто задаваемые вопросы

Урок «Защита конечных точек STOMP с помощью Spring Security» бесплатный?

Да — полный текст урока «Защита конечных точек STOMP с помощью Spring Security» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebSockets & Real-Time Systems with Spring, подпишись на CoddyKit PRO. Курс WebSockets & Real-Time Systems with Spring содержит 4 уроков всего.

Чему я научусь в уроке «Защита конечных точек STOMP с помощью Spring Security»?

Узнайте, как выполнять аутентификацию и авторизацию обмена сообщениями STOMP в Spring, защищая рукопожатие, адресаты и сообщения для отдельных пользователей от несанкционированного доступа. Ты практикуешь WebSockets & Real-Time Systems with Spring с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebSockets & Real-Time Systems with Spring?

Предыдущий опыт не требуется. WebSockets & Real-Time Systems with Spring на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Защита конечных точек STOMP с помощью Spring Security»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebSockets & Real-Time Systems with Spring?

Да. Каждый урок WebSockets & Real-Time Systems with Spring включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Знакомство с протоколом STOMP
  2. Настройка STOMP в Spring
  3. Отправка и получение сообщений STOMP
  4. Защита конечных точек STOMP с помощью Spring Security
← Назад к WebSockets & Real-Time Systems with Spring