0Pricing
WebSockets & Real-Time Systems with Spring · 课时

身份验证与授权

为 WebSocket 用户实施身份验证,并根据角色和权限授权访问。

身份验证与授权 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「身份验证与授权」这节课中我会学到什么?

为 WebSocket 用户实施身份验证,并根据角色和权限授权访问。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 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