Spring Boot应用中的Websocket - 获取403 Forbidden错误
当我在eclipse中运行时(没有使用Spring Boot),我可以使用sockjs/stompjs从客户端连接到Websocket。
但是,当我为Websocket代码创建了一个Spring Boot jar(gradlew build),并运行java -jar websocket-code.jar时,我会得到一个403错误来连接Websocket。
我对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'
}
更新:
添加了一个CORS过滤器,使用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
我请求的来源在允许来源列表中。但是日志中仍然会收到“请求被拒绝”的消息。
setAllowedOrigins("http://somehost")
。这可能看起来很清晰,但当我在这篇文章上遇到困难时,我还是有必要说一下它 :-) - FencerWebSocketConfigurer
中注册的原始网络套接字。在public void registerWebSocketHandlers(WebSocketHandlerRegistry registry)
方法中,您可以调用registry.addHandler(new MyWebSocketHandler(), "/some-path").setAllowedOrigins("*")
。不幸的是,WebSocket无法告诉您它是一个CORS问题……403错误会让人误解。 - user5365075