refactor: WebSocket 优化

This commit is contained in:
ray
2024-08-23 22:25:21 +08:00
parent 2b43ebd8a3
commit c2a28147ac
4 changed files with 7 additions and 6 deletions

View File

@@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version> <!-- lookup parent from repository -->
<version>3.3.2</version> <!-- lookup parent from repository -->
<relativePath/>
</parent>

View File

@@ -5,6 +5,7 @@ import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.youlai.system.common.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.messaging.Message;
@@ -39,11 +40,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
registry
// 注册 /ws 的端点
.addEndpoint("/ws")
// 允许跨域的 WebSocket 连接
// 允许跨域
.setAllowedOriginPatterns("*")
// 启用 SockJS (浏览器不支持WebSocketSockJS 将会提供兼容性支持)
.withSockJS();
registry.addEndpoint("/ws-app").setAllowedOriginPatterns("*"); // 注册了一个 /ws-app 的端点,支持 uni-app 的 ws 连接协议
}
@@ -74,7 +74,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
public Message<?> preSend(@NotNull Message<?> message, @NotNull MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
// 如果是连接请求CONNECT 命令),从请求头中取出 token 并设置到认证信息中
if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {

View File

@@ -81,6 +81,7 @@ security:
key: SecretKey012345678901234567890123456789012345678901234567890123456789
# JWT 有效期(单位:秒)
ttl: 7200
# 白名单列表
ignore-urls:
- /v3/api-docs/**
- /doc.html
@@ -91,7 +92,6 @@ security:
- /swagger-ui.html
- /api/v1/auth/captcha
- /ws/**
- /ws-app/**
# 文件存储配置
oss:

View File

@@ -59,11 +59,13 @@ mybatis-plus:
# 安全配置
security:
# JWT 配置
jwt:
# JWT 秘钥
key: SecretKey012345678901234567890123456789012345678901234567890123456789
# JWT 有效期(单位:秒)
ttl: 7200
# 白名单列表
ignore-urls:
- /v3/api-docs/**
- /doc.html
@@ -74,7 +76,6 @@ security:
- /swagger-ui.html
- /api/v1/auth/captcha
- /ws/**
- /ws-app/**
# 文件存储配置
oss: