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

การพิสูจน์ตัวตนและการกำหนดสิทธิ์

นำการพิสูจน์ตัวตนสำหรับผู้ใช้ WebSocket ไปใช้ และอนุญาตการเข้าถึงตามบทบาทและสิทธิ์

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

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

Securing Your Real-Time Interactions

Welcome to the final lesson in securing your WebSocket endpoints! Today, we'll dive into how to authenticate users and authorize their actions.

Authentication is about verifying who a user is (e.g., logging in). Authorization is about determining what an authenticated user is allowed to do (e.g., access admin features).

Both are vital for preventing unauthorized access and ensuring data integrity in your real-time applications.

Bridging HTTP Authentication

When using Spring Security, it cleverly bridges your existing HTTP session authentication to your WebSocket sessions. This means if a user is already logged in via your web application, they are automatically authenticated for WebSocket communication as well.

Spring associates the authenticated user's Principal (representing the user) with their WebSocket session, making it easy to identify who is sending or receiving messages.

Knowing Your WebSocket User

Once a user is authenticated, you can access their Principal object directly within your STOMP message-handling methods. This allows you to personalize responses or log user-specific actions.

Try running this simple Java example to understand the concept of a Principal:

import java.security.Principal;

public class Main {
  public static void main(String[] args) {
    // In a Spring @MessageMapping method,
    // you'd get Principal directly from the framework.
    // This simulates an authenticated user for demonstration.
    Principal currentUser = () -> "alice@example.com";
    System.out.println("Current user: " + currentUser.getName());
  }
}

Path-Based Access Control

Spring Security provides a powerful way to authorize access to WebSocket destinations (topics or queues) using a MessageMatcherRegistry. This allows you to define rules based on the STOMP destination path.

You typically configure these rules in your WebSocketSecurityConfigurer or WebSocketMessageBrokerConfigurer, granting or denying access based on roles or authentication status.

Securing Specific Destinations

Here's an example of how to use MessageMatcherRegistry to secure WebSocket destinations. Notice how different paths require different roles or simply authentication.

This code snippet is part of a Spring configuration and is not runnable as a standalone Java program.

// Inside a WebSocketSecurityConfigurer or similar class
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        .simpDestMatchers("/topic/public").permitAll() // Anyone can subscribe
        .simpDestMatchers("/topic/admin").hasRole("ADMIN") // Only admins
        .simpDestMatchers("/app/**").authenticated() // All app messages need auth
        .anyMessage().denyAll(); // Deny everything else by default
}

Fine-Grained Method Security

For even more granular control, you can apply Spring Security's @PreAuthorize annotations directly to your @MessageMapping methods. This allows you to define authorization rules that are evaluated before the method even executes.

This approach is excellent for complex logic, like checking specific permissions or validating message content against the authenticated user.

Restricting Message Sending

Let's look at an example using @PreAuthorize. This ensures that only users with the 'MODERATOR' role can send messages to an administrative broadcast channel, while regular users can send standard chat messages.

This code snippet is part of a Spring controller and is not runnable as a standalone Java program.

// Inside a @Controller or @MessageMapping class
@MessageMapping("/chat.sendMessage")
@PreAuthorize("hasRole('USER')")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage, Principal principal) {
    System.out.println("User " + principal.getName() + " sent: " + chatMessage.getContent());
    // ... further processing ...
    return chatMessage;
}

@MessageMapping("/admin.broadcast")
@PreAuthorize("hasRole('MODERATOR')")
public void broadcastAdminMessage(@Payload String message) {
    System.out.println("Admin broadcast: " + message);
    // ... send admin message to all admins ...
}

Secure Private Messages

One of the great features of STOMP with Spring is its built-in support for user-specific destinations, typically prefixed with /user/.

When a client subscribes to, for example, /user/queue/notifications, Spring ensures that messages sent to this destination are routed only to the authenticated user associated with that session. This provides inherent privacy and authorization for one-on-one communication.

Custom Authentication Flow

While Spring Security's integration often covers many cases, you might encounter scenarios requiring custom authentication (e.g., using JWT tokens in WebSocket headers, independent of HTTP sessions).

For these advanced cases, you can implement a ChannelInterceptor. This allows you to inspect and modify incoming STOMP messages, extract authentication tokens, and manually set the Principal in the message header before it reaches your controllers.

Test Your Knowledge

Which of the following are valid and effective ways to implement authorization for WebSocket messages in Spring?

Recap: Securing Real-Time

You've learned how to implement authentication and authorization for your Spring WebSocket applications! Key takeaways:

  • Spring Security seamlessly integrates HTTP session authentication with WebSockets.
  • Access the authenticated user via the Principal object.
  • Use MessageMatcherRegistry for path-based authorization on STOMP destinations.
  • Apply @PreAuthorize for granular, method-level authorization.
  • Leverage the /user destination for inherently secure private messaging.
  • For advanced needs, ChannelInterceptor allows custom authentication flows.

By implementing these strategies, you can build robust and secure real-time features!

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

บทเรียน “การพิสูจน์ตัวตนและการกำหนดสิทธิ์” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การพิสูจน์ตัวตนและการกำหนดสิทธิ์”

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

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

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

บทเรียน “การพิสูจน์ตัวตนและการกำหนดสิทธิ์” ใช้เวลานานแค่ไหน

บทเรียน 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