Spring Boot 应用程序中的 Websocket - 获取 403 禁止访问

2022-09-01 07:09:56

Spring Boot 应用程序中的 Websocket - 获取 403 禁止访问

当我在eclipse中运行它时,我可以使用sockjs / stompjs从客户端连接到websocket(没有弹簧靴)。

但是当我为websocket代码创建一个Spring boot jar(gradlew build)并运行java -jar websocket-code时.jar我收到一个403错误连接到websocket。

我没有对网络袜子进行身份验证。我有一个CORS过滤器,并认为在请求/响应中具有所有标头。

以下是我的 build.gradle

apply plugin: 'java'
apply plugin: 'spring-boot'
apply plugin: 'war'

sourceCompatibility = 1.7
version = '1.0'

repositories {
    mavenCentral()
}

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE")
    }
}

configurations {
    compile.exclude module: "spring-boot-starter-tomcat"
}

dependencies {
    compile "org.springframework:spring-web:$spring_version"
    compile "org.springframework:spring-webmvc:$spring_version"
    compile "org.springframework:spring-websocket:$spring_version"
    compile "org.springframework:spring-messaging:$spring_version"
    compile "org.springframework.boot:spring-boot-starter-websocket"
    compile "org.springframework.boot:spring-boot-starter-web"
    compile "com.fasterxml.jackson.core:jackson-databind:2.6.2"
    compile "com.fasterxml.jackson.core:jackson-core:2.6.2"
    compile "com.fasterxml.jackson.core:jackson-annotations:2.6.2"
    compile "org.springframework.amqp:spring-rabbit:1.3.5.RELEASE"
    compile("org.springframework:spring-tx")
    compile("org.springframework.boot:spring-boot-starter-web:1.2.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-jetty:1.2.6.RELEASE")
    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile "org.springframework:spring-test:$spring_version"
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.5'
}

更新:

添加了一个带有 response.setHeader(“Access-Control-Allow-Origin”, “http://localhost:8089");

在客户端的 firebug 中

Request Headers 
Origin  
http://localhost:8089

Response Headers
Access-Control-Allow-Origin
http://localhost:8089

Server Logs
2015-10-02 16:57:31.372 DEBUG 1848 --- [qtp374030679-14] o.s.w.s.s.t.h.DefaultSockJsService       : Request rejected, Origin header value http://localhost:8089 not allowed

我从中请求的源位于允许源列表中。日志中仍收到“请求被拒绝”消息。


答案 1

我遇到了类似的问题,并通过将允许的源设置为“*”在WebSocketConfig中修复了它。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // the endpoint for websocket connections
        registry.addEndpoint("/stomp").setAllowedOrigins("*").withSockJS();
    }

    // remaining config not shown as not relevant
}

答案 2

尝试添加

registry.addEndpoint("/your-end-point").setAllowedOrigins("*").withSockJS();

“你的终点”是由@SendTo在控制器中注册的,我猜


推荐