添加 Spring Boot Security 时 Websocket 连接失败

问题描述 投票:0回答:1

在一个项目中,我必须实现用户之间的实时聊天。为此,我决定使用 Websockets。 我目前有一个用 React 编写的前端客户端和一个用 Java 编写的 Spring boot 后端。

客户端能够连接到服务器的 Websocket,但是一旦我添加

spring-boot-starter-security
依赖项,它就会中断,并出现以下错误(在浏览器控制台中,服务器控制台中没有错误或信息):
WebSocket connection to 'ws://localhost:8080/peer-tutoring-chat-websocket' failed

WebSocket connection error

注意:我需要安全依赖,因为我需要验证 JWT 令牌并管理后端的用户角色,因此不能删除它。


有趣的事情之一是,一旦在

pom.xml
文件中添加依赖项,代码就会中断(无需更改或添加与后端安全相关的任何新代码)。这让我认为问题与所使用的库内的冲突有关。

我尝试过的:

  • 我检查了
    spring-boot-starter-security
    的传递依赖关系,希望找到一个与另一个冲突的依赖关系,但没有成功。
  • 我尝试使用旧版本的
    spring-boot-starter-security
    依赖项,但没有成功。

任何人都可以发现问题或者过去处理过类似的情况吗?谢谢你。

pom.xml
文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.somepackage</groupId>
    <artifactId>backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>backend</name>
    <description>somedescription</description>
    <properties>
        <java.version>21</java.version>
        <spring-cloud-azure.version>5.9.1</spring-cloud-azure.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>jwks-rsa</artifactId>
            <version>0.22.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.17.2</version>
        </dependency>
        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <version>4.2.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

WebSocketConfig
文件:

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                .addEndpoint("/mysocket-websocket")
                .setAllowedOriginPatterns("*");
    }

}

客户提出请求:

import { Client } from "@stomp/stompjs";       // "@stomp/stompjs": "^7.0.0"

useEffect(() => {
        if (selectedChat) {
            fetchChatMessages(selectedChat.id).then((data: MessageType[]) => {                
                setMessages(data);
            }).catch((error) => {
                console.log(error);
            });
        }

        const client = new Client({
            brokerURL: 'ws://localhost:8080/mysocket-websocket',
            connectHeaders: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
            },
            onConnect: () => {
                console.log("Connected to socket")
            },
            onStompError: (err) => {
                console.error(err);
            }
        });

        client.activate();

        // Clean up function to disconnect when the component is unmounted
        return () => {
            client.deactivate();
        };
    }, [selectedChat]);
java spring spring-boot spring-security spring-websocket
1个回答
0
投票

一旦您将依赖项添加到项目中,Spring Boot 就会添加 AutoConfiguration。请查看:https://www.baeldung.com/spring-boot-security-autoconfiguration

如果您添加

application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
,它应该会再次起作用。

© www.soinside.com 2019 - 2024. All rights reserved.