0Pricing
WebSockets & Real-Time Systems with Spring · บทเรียน

การผสาน Spring Security

ผสาน Spring Security เพื่อปกป้องการเชื่อมต่อ WebSocket และกระแสข้อความ

การผสาน Spring Security เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Real-Time Systems with Spring และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Secure Your Real-Time Apps

Integrating real-time features like WebSockets into your applications is exciting, but security is paramount. Just like traditional HTTP endpoints, your WebSocket connections and message flows need protection.

  • Data Integrity: Prevent unauthorized tampering with messages.
  • Confidentiality: Ensure only authorized users can read sensitive data.
  • Access Control: Control who can connect, send messages, or subscribe to topics.

Spring Security offers a powerful framework to secure your WebSocket endpoints effectively.

Essential Security Dependencies

To begin securing your Spring WebSocket application, you'll need to add the necessary Spring Security dependencies to your project. If you're using Spring Boot, these are typically straightforward.

You'll primarily need:

  • spring-boot-starter-security: Provides core Spring Security features.
  • spring-security-messaging: Specifically for securing Spring's messaging infrastructure, including WebSockets and STOMP.

If you used Spring Initializr, ensure these are included in your pom.xml (Maven) or build.gradle (Gradle).

HTTP Security Foundation

WebSocket connections typically start with an HTTP handshake. This means that your existing HTTP security configuration in Spring Security forms the foundation for WebSocket security.

Before messages flow over WebSockets, the user is usually authenticated via a standard HTTP login process. Spring Security then leverages this authenticated session to secure subsequent WebSocket interactions. A minimal HTTP security setup might look like this:

@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .formLogin(withDefaults()); return http.build(); }

This ensures all HTTP requests require authentication, which is crucial for the WebSocket handshake.

Activate WebSocket Security

Once you have your basic HTTP security in place, you need to tell Spring Security to secure your WebSocket messages. This is done by adding the @EnableWebSocketSecurity annotation.

You'll typically place this annotation on a configuration class that extends WebSocketMessageBrokerConfigurer. This allows you to customize both the WebSocket message broker and its security rules within a single configuration.

The @EnableWebSocketSecurity annotation enables Spring Security's message-based authorization for STOMP messages, allowing you to define fine-grained access control.

Guarding STOMP Destinations

Spring Security integrates with the STOMP protocol, allowing you to secure specific message destinations. You achieve this by overriding the configureInbound() method in your WebSocketMessageBrokerConfigurer.

Inside this method, you use a MessageSecurityMetadataSourceRegistry to define rules based on destination patterns:

  • .simpDestMatchers("/app/private-chat").authenticated(): Only authenticated users can send messages to this destination.
  • .simpDestMatchers("/topic/admin-updates").hasRole("ADMIN"): Only users with the 'ADMIN' role can subscribe to this topic.

This provides powerful, URL-like security for your real-time messages.

User Identity in WebSockets

A key benefit of integrating Spring Security is how it handles user authentication. When a user connects to a WebSocket endpoint after authenticating via HTTP, Spring Security automatically associates their Principal (user identity) with the WebSocket session.

This means that any security rules you define for WebSocket messages can leverage the same authentication and authorization context as your regular HTTP requests. You don't need to re-authenticate users separately for WebSockets.

The Principal object will be available in the WebSocket session, allowing you to make authorization decisions based on the authenticated user's roles or details.

Control Message Sending

You can define authorization rules for messages that clients send to the server (e.g., publishing to an /app destination). This is done using .simpMessageSending() in the MessageSecurityMetadataSourceRegistry.

For example, to allow only authenticated users to send messages:

messages.simpMessageSending().authenticated();

Or, to restrict sending to a specific role:

messages.simpMessageSending().hasRole("USER");

This ensures that only authorized clients can publish messages to your application's internal handlers.

Restrict Subscriptions

Controlling who can subscribe to a particular topic is equally important. You can use .simpSubscribe() within the MessageSecurityMetadataRegistry to apply authorization rules for subscription requests.

For instance, to allow anyone to subscribe to a public topic, but only admins to a private one:

messages .simpSubscribeDestMatchers("/topic/public").permitAll() .simpSubscribeDestMatchers("/topic/private-admin").hasRole("ADMIN");

This prevents unauthorized users from receiving messages meant for specific groups or roles.

Example: Securing Destinations

Let's see a minimal Spring Boot application that integrates Spring Security to protect WebSocket STOMP destinations. This example defines different access rules for public, admin, and authenticated-only channels.

When this application starts, it enables WebSocket security and configures rules for sending and subscribing to specific paths. For a real application, you'd also need an HTTP security config (as mentioned in Scene 3) and a user service for authentication.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.config.annotation.web.socket.EnableWebSocketSecurity;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;

@SpringBootApplication
@EnableWebSocketMessageBroker // Enables STOMP over WebSockets
@EnableWebSocketSecurity // Enables Spring Security for WebSocket messages
@Configuration
public class Main implements WebSocketMessageBrokerConfigurer {

  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
    System.out.println("WebSocket Security Demo Started!");
    System.out.println("Access at ws://localhost:8080/ws");
  }

  // Configure STOMP endpoints (e.g., /ws)
  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws").withSockJS();
  }

  // Configure message broker (e.g., /topic, /app)
  @Override
  public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/topic", "/queue");
    registry.setApplicationDestinationPrefixes("/app");
  }

  // Configure message security rules for inbound messages
  @Override
  protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
      // Allow anyone to subscribe to /topic/public
      .simpSubscribeDestMatchers("/topic/public").permitAll()
      // Only ADMIN role can subscribe to /topic/admin
      .simpSubscribeDestMatchers("/topic/admin").hasRole("ADMIN")
      // Authenticated users can send messages to /app/private
      .simpDestMatchers("/app/private").authenticated()
      // Deny all other message types/destinations by default
      .anyMessage().denyAll();
  }
}

Configure Access

Imagine you're building a real-time application with chat rooms. You need to set up the following security rules for your STOMP messages:

  • Clients can send messages to /app/general-chat only if they are authenticated.
  • Only users with the MODERATOR role can subscribe to /topic/moderator-alerts.
  • All other message types or destinations not explicitly allowed should be denied by default.

Which Spring Security rules would you apply from the options below?

Recap: Secure Your Real-Time Apps

You've learned how to integrate Spring Security with your WebSocket applications to protect real-time communication. Here's a quick summary:

  • Add spring-boot-starter-security and spring-security-messaging dependencies.
  • Ensure a basic HTTP security configuration exists, as WebSocket security builds on it.
  • Use @EnableWebSocketSecurity to activate message-level security.
  • Override configureInbound() in WebSocketMessageBrokerConfigurer to define rules.
  • Utilize MessageSecurityMetadataSourceRegistry with .simpDestMatchers(), .simpMessageSending(), and .simpSubscribeDestMatchers() to apply authorization.
  • Leverage .authenticated(), .hasRole(), and .permitAll(), along with .anyMessage().denyAll() for a robust security posture.

By following these steps, you can ensure your real-time applications are secure and reliable!

คำถามที่พบบ่อย

บทเรียน “การผสาน Spring Security” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสาน Spring Security” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสาน Spring Security”

ผสาน Spring Security เพื่อปกป้องการเชื่อมต่อ WebSocket และกระแสข้อความ คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การผสาน Spring Security” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม

ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ประเด็นด้านความปลอดภัยของ WebSocket
  2. การผสาน Spring Security
  3. การพิสูจน์ตัวตนและการกำหนดสิทธิ์
  4. การเข้ารหัสทราฟฟิกด้วย TLS และ wss://
← กลับไปที่ WebSockets & Real-Time Systems with Spring