所以我必须说所有的websocket教程/示例看起来都很简单,但是你似乎真的需要挖掘才能找到简单例子中遗漏的非常重要的信息。我在前端使用带有SockJS的Spring 4 Stomp消息代理时,我的webapp存在很多问题。
目前,如果我在没有启用SockJS()的情况下向StompEndpointRegistry添加端点,然后使用dojo的dojox / socket在前端声明我的套接字,Firefox 28将打开websocket就好了。但是,我需要在IE8和IE9中支持,所以我切换到了SockJS。使用AbstractAnnotationConfigDispatcherServletInitializer,我花了很多时间来弄清楚如何确保所有过滤器和servlet都设置为使用异步(在Web上非常稀疏的文档)。一旦我解决了这个问题,我现在可以在Firefox中使用它,但只能使用xhr_streaming。将sessionCookieNeeded设置为true,IE9默认尝试使用iframe进行连接,但是,它失败了:
LOG: Opening Web Socket...
LOG: Opening transport: iframe-htmlfile url:rest/hello/904/ft3apk1g RTO:1008
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false)
LOG: Opening transport: iframe-xhr-polling url:rest/hello/904/bf63eisu RTO:1008
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false)
LOG: Whoops! Lost connection to undefined
如果我将所需的cookie设置为false,IE将使用xdr-streaming并且工作正常,但是,它会丢失请求中的jsessionid cookie,反过来我失去了在控制器中获取Principal的能力,这对于我。我在spring security中启用了相同的origin x frame header,并且我已经验证了请求中是否存在标题,但它没有帮助。所以我想知道如何A)让Spring和SockJS在Firefox中使用WebSocket传输正确协商,并且B)让IE8和9正确使用iframe传输,这样我就可以保留cookie。
这是我的配置/代码:
网络应用配置:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
Map<String, ? extends FilterRegistration> registrations = servletContext.getFilterRegistrations();
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// this is needed for async support for websockets/sockjs
registration.setInitParameter("dispatchOptionsRequest", "true");
registration.setAsyncSupported(true);
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SecurityConfig.class, Log4jConfig.class, PersistenceConfig.class, ServiceConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// loading the Initializer class from the dispatcher servlet context ensures it only executes once,
// as the ContextRefreshedEvent fires once from the root context and once from the dispatcher servlet context
return new Class[]{SpringMvcConfig.class, WebSocketConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{
"/rest/*",
"/index.html",
"/login.html",
"/admin.html",
"/index/*",
"/login/*",
"/admin/*"
};
}
@Override
protected Filter[] getServletFilters() {
OpenEntityManagerInViewFilter openEntityManagerInViewFilter = new OpenEntityManagerInViewFilter();
openEntityManagerInViewFilter.setBeanName("openEntityManagerInViewFilter");
openEntityManagerInViewFilter.setPersistenceUnitName("HSQL");
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
return new javax.servlet.Filter[]{openEntityManagerInViewFilter, encodingFilter};
}
}
Spring MVC config:
@Configuration
@EnableWebMvc
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@ComponentScan(basePackages = "x.controllers") // Only scan for controllers. Other classes are scanned in the parent's root context
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJacksonHttpMessageConverter());
converters.add(marshallingMessageConverter());
super.configureMessageConverters(converters);
}
@Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public JacksonAnnotationIntrospector jacksonAnnotationIntrospector() {
return new JacksonAnnotationIntrospector();
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(jacksonAnnotationIntrospector());
mapper.registerModule(new JodaModule());
mapper.registerModule(new Hibernate4Module());
return mapper;
}
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setObjectMapper(objectMapper());
return messageConverter;
}
@Bean(name = "marshaller")
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.x);
return marshaller;
}
@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
return new MarshallingHttpMessageConverter(
jaxb2Marshaller(),
jaxb2Marshaller()
);
}
}
Spring root context config:
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.x.services"}, // scan for all annotated classes for the root context OTHER than controllers -- those are in the child web context. also don't rescan these config files
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class),
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class)
}
)
public class ServiceConfig {
@Bean
public DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping() {
DefaultAnnotationHandlerMapping handlerMapping = new DefaultAnnotationHandlerMapping();
handlerMapping.setAlwaysUseFullPath(true);
handlerMapping.setDetectHandlersInAncestorContexts(true);
return handlerMapping;
}
@Bean
public DefaultConversionService defaultConversionService() {
return new DefaultConversionService();
}
@Bean(name = "kmlContext")
public JAXBContext kmlContext() throws JAXBException {
return JAXBContext.newInstance("net.opengis.kml");
}
@Bean(name = "ogcContext")
public JAXBContext ogcContext() throws JAXBException {
return JAXBContext.newInstance("net.x");
}
}
Spring security:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider();
TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices();
List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2);
authenticationProviders.add(rememberMeAuthenticationProvider);
authenticationProviders.add(customAuthenticationProvider);
AuthenticationManager authenticationManager = authenticationManager(authenticationProviders);
http
.csrf().disable()
//.headers().disable()
.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
.and()
.authenticationProvider(customAuthenticationProvider)
.addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices))
.rememberMe().rememberMeServices(tokenBasedRememberMeServices)
.and()
.authorizeRequests()
.antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll()
.antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER")
.antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN")
.and()
.formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/login")
.and()
.logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
return new ProviderManager(authenticationProviders);
}
@Bean
public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
return new TokenBasedRememberMeServices("testKey", userDetailsService);
}
@Bean
public AuthenticationProvider rememberMeAuthenticationProvider() {
return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey");
}
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
WebSocket消息代理配置:
@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
SockJsServiceRegistration registration = registry.addEndpoint("/hello").withSockJS().setClientLibraryUrl("http://localhost:8084/swtc/js/sockjs-0.3.4.min.js");
registration.setWebSocketEnabled(true);
//registration.setSessionCookieNeeded(false);
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(8);
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(8);
}
}
WebSocket控制器:
@Controller
public class WebSocketController {
@MessageMapping({"/hello", "/hello/**"})
@SendTo("/topic/greetings")
// in order to get principal, you must set cookiesNeeded in WebSocketConfig, which forces IE to use iframes, which doesn't seem to work
public AjaxResponse<String> greeting(@Payload PointRadiusRequest prr, Principal principal) throws Exception {
Thread.sleep(3000); // simulated delay
AjaxResponse<String> ajaxResponse = new AjaxResponse<String>();
ajaxResponse.setValue(principal.getName());
ajaxResponse.setSuccess(true);
return ajaxResponse;
}
}
最后,我的html中的javascript用于测试:
<script>
// test/prototype websocket code
stompClient = null;
window.connect = function() {
var options = {protocols_whitelist: ["websocket", "xhr-streaming", "xdr-streaming", "xhr-polling", "xdr-polling", "iframe-htmlfile", "iframe-eventsource", "iframe-xhr-polling"], debug: true};
wsSocket = new SockJS('rest/hello', undefined, options);
stompClient = Stomp.over(wsSocket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(message) {
console.info("response: ", JSON.parse(message.body));
});
});
};
window.disconnect = function() {
stompClient.disconnect();
console.log("Disconnected");
};
window.sendName = function() {
stompClient.send("/app/hello", {}, JSON.stringify({'latitude': 12, 'longitude': 123.2, radius: 3.14}));
};
</script>
当我在Firefox中连接时,这就是我在控制台中看到的内容:
>>> connect()
connecting
/swtc/ (line 109)
Opening Web Socket...
stomp.js (line 130)
undefined
GET http://localhost:8084/swtc/rest/hello/info
200 OK
202ms
sockjs....min.js (line 27)
Opening transport: websocket url:rest/hello/007/xkc17fkt RTO:912
sockjs....min.js (line 27)
SyntaxError: An invalid or illegal string was specified
...3,reason:"All transports failed",wasClean:!1,last_event:g})}f.readyState=y.CLOSE...
sockjs....min.js (line 27)
Closed transport: websocket SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
sockjs....min.js (line 27)
Opening transport: xhr-streaming url:rest/hello/007/8xz79yip RTO:912
sockjs....min.js (line 27)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_streaming
200 OK
353ms
sockjs....min.js (line 27)
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
�
stomp.js (line 130)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_send
204 No Content
63ms
<<< CONNECTED
user-name:first.mi.last
heart-beat:0,0
version:1.1
�
stomp.js (line 130)
connected to server undefined
stomp.js (line 130)
Connected: CONNECTED
version:1.1
heart-beat:0,0
user-name:xxx
>>> SUBSCRIBE
id:sub-0
destination:/topic/greetings
�
stomp.js (line 130)
POST http://localhost:8084/swtc/rest/hello/007/8xz79yip/xhr_send
204 No Content
57ms
/ info响应是:
{"entropy":441118013,"origins":["*:*"],"cookie_needed":true,"websocket":true}
注意尝试建立websocket连接时出现奇怪的字符串错误。我猜这是我的问题的根源,但我没有做任何有趣的事情,我不知道是什么导致了它。
在IE中,这是网络流量。 iframe.html文件似乎构建正确,但它无法建立与后端的连接。
URL Method Result Type Received Taken Initiator Wait Start Request Response Cache read Gap
/swtc/rest/hello/info?t=1399328502157 GET 200 application/json 411 B 328 ms 0 47 281 0 0 2199
/swtc/rest/hello/iframe.html GET 200 text/html 0.97 KB 156 ms frame navigate 328 0 156 0 0 2043
/swtc/js/sockjs-0.3.4.min.js GET 304 application/javascript 157 B < 1 ms <script> 484 0 0 0 0 2043
/swtc/rest/hello/iframe.html GET 304 text/html 191 B < 1 ms frame navigate 2527 0 0 0 0 0
/swtc/js/sockjs-0.3.4.min.js GET 304 application/javascript 157 B < 1 ms <script> 2527 0 0 0 0 0
信息响应如下所示:
{"entropy":-475136625,"origins":["*:*"],"cookie_needed":true,"websocket":true}
如果有人想查看请求或响应标头,请告诉我。
更新1:
罗森,谢谢你的回应。我所知道的关于Spring 4的一切我都是从你那里学到的:)Firefox实际上并没有(完全)工作,我无法获得websocket会话,它会降级为xhr-streaming。使用xhr-streaming,没有问题,但我希望有一个真正的websocket会话。
使用IE浏览器,我不确定删除标题会确认什么?我认为x帧标题只会影响iframe会话,而iframe会话根本不起作用。当我禁用require cookie时,IE使用xdr-streaming(并且可以工作,虽然无法获取Principal)。一旦我启用了cookie,IE就可以正确地使用iframe来尝试ATTEMPTS。但即使标题到位,所有尝试都会失败:
http://localhost:8084/swtc/rest/hello/info?t=1399328502157
Key Value
Response HTTP/1.1 200 OK
Server Apache-Coyote/1.1
X-Frame-Options SAMEORIGIN
Access-Control-Allow-Origin http://localhost:8084
Access-Control-Allow-Credentials true
Cache-Control no-store, no-cache, must-revalidate, max-age=0
Content-Type application/json;charset=UTF-8
Content-Length 78
Date Mon, 05 May 2014 22:21:42 GMT
LOG: Opening Web Socket...
LOG: Opening transport: iframe-htmlfile url:rest/hello/904/ft3apk1g RTO:1008
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false)
LOG: Opening transport: iframe-xhr-polling url:rest/hello/904/bf63eisu RTO:1008
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=1006, reason=Unable to load an iframe (onload timeout), wasClean=false)
LOG: Whoops! Lost connection to undefined
iframe-htmlfile和iframe-xhr-polling都失败了。我确实清除IE中每次刷新的缓存,并且我确实在SockJS中启用了调试模式。我会在IE中使用xdr-streaming很好,但我真的需要jsessionid cookie。
有什么想法吗?
另一方面,如果客户端库代码支持相对路径(它实际上构建了具有相对路径的html文件并且应该工作,但仍然在日志中产生错误),那将是非常好的,即:
SockJsServiceRegistration registration = registry.addEndpoint("/hello").withSockJS().setClientLibraryUrl("js/sockjs-0.3.4.min.js");
这样可以减少对生产的部署。
更新2:
快速摘要:没有变化。
这是我尝试使用安全配置中的.headers()。和()连接IE9:
LOG: Opening Web Socket...
LOG: Opening transport: iframe-htmlfile url:rest/hello/924/1ztfjm7z RTO:330
LOG: Closed transport: iframe-htmlfile SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
LOG: Opening transport: iframe-xhr-polling url:rest/hello/924/cgq8_s5j RTO:330
LOG: Closed transport: iframe-xhr-polling SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
LOG: Whoops! Lost connection to undefined
/ info:
的请求标头Key Value
Request GET /swtc/rest/hello/info?t=1399404419358 HTTP/1.1
Accept */*
Origin http://localhost:8084
Accept-Language en-US
UA-CPU AMD64
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Host localhost:8084
Connection Keep-Alive
Cache-Control no-cache
和响应标题:
Key Value
Response HTTP/1.1 200 OK
Server Apache-Coyote/1.1
X-Content-Type-Options nosniff
X-XSS-Protection 1; mode=block
Cache-Control no-cache, no-store, max-age=0, must-revalidate
Pragma no-cache
Expires 0
X-Frame-Options DENY
Access-Control-Allow-Origin http://localhost:8084
Access-Control-Allow-Credentials true
Cache-Control no-store, no-cache, must-revalidate, max-age=0
Content-Type application/json;charset=UTF-8
Content-Length 78
Date Tue, 06 May 2014 19:26:59 GMT
Firefox没有任何区别。我尝试打开websocket时遇到同样奇怪的字符串错误,然后回到xhr-streaming:
Opening transport: websocket url:rest/hello/849/fy_06t1v RTO:342
SyntaxError: An invalid or illegal string was specified
Closed transport: websocket SimpleEvent(type=close, code=2007, reason=Transport timeouted, wasClean=false)
Opening transport: xhr-streaming url:rest/hello/849/2r0raiz8 RTO:342
http://localhost:8084/swtc/rest/hello/849/2r0raiz8/xhr_streaming
Web Socket Opened...
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
答案 0 :(得分:3)
鉴于它在FF和IE中使用sessionCookieNeeded = false,我猜这个问题与X-Frame-Options标题有关。
您的配置似乎正确。特别是针对Spring Security:
.headers().addHeaderWriter(
new XFrameOptionsHeaderWriter(
XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN)).and()
这也适用于SockJS:
setClientLibraryUrl("http://localhost:8084/swtc/js/sockjs-0.3.4.min.js");
我建议尝试禁用标题,以确认是否是问题,即:
.headers().and()
还要确保没有涉及发送相同响应的浏览器缓存问题。因此,请检查X-Frame-Options值的实际响应标头。
为此,我强烈建议通过SockJS构造函数的options参数启用SockJS客户端调试模式。
答案 1 :(得分:3)
由于SockJS在尝试WebSocket连接时产生了一个奇怪的字符串错误,然后回到xhr_streaming,我决定加载.js文件的非缩小版本并在Firebug中调试它以查看发生了什么。事实证明,SockJS不喜欢相对的URL,这种情况很糟糕。
对于我的大部分REST / AJAX服务,我将/ rest / *映射到我的调度程序servlet,通常在每个控制器上都有一个@RequestMapping,在每个控制器方法上都有另一个@RequestMapping。使用Dojo,我通过指定URL "rest/<controller>/<method>"
来进行AJAX调用。
我和SockJS一样尝试过同样的事情。我只是指着“休息/你好”。我将其更改为完全限定的URL“http://localhost:8084/swtc/rest/hello
”,然后firefox可以很好地构建websocket传输层。我跳到IE浏览器进行快速测试,果然,它构建了iframe会话并且工作得很好。
这个愚蠢的小问题。我不想在任何地方指定非相对URL,因为这个代码库是在多个开发人员之间共享的,所有开发人员都部署到不同的服务器进行测试,并部署到生产环境。我想在前端我可以使用window.doc.URL动态构建URL,但是当指定setClientLibraryUrl时,让AbstractWebSocketMessageBrokerConfigurer在部署中自动工作会更麻烦。
无论哪种方式,孩子都不要使用SockJS的相对路径。
答案 2 :(得分:0)
我发现IE9在今天经过一些调查后发现我需要将 devel 选项传递给创建SockJS的调用。
var protocols = { protocols_whitelist: ["websocket", "xhr-streaming", "xdr-streaming", "xhr-polling", "xdr-polling", "iframe-htmlfile", "iframe-eventsource", "iframe-xhr-polling"]};
var opt = {debug: false, devel: true}
var socket = new SockJS('/Application/wscomms', protocols, opt);
var stompClient = Stomp.over(socket);
在sockjs-0.3.4.js文件中(在第1749行)我发现时间被附加到iFrame URL
if (that.ri._options.devel) {
iframe_url += '?t=' + (+new Date);
}
我注意到如果没有作为选项传入,则开发选项设置为false。
您还会注意到我能够将相对URL传递给正在运行的SockJS。我也有Rossen所示的Spring Security配置和WebSocketConfig setClientLibraryUrl()。
我也发现我能够拥有
.setSessionCookieNeeded(true);
我使用的是Spring 4.0.1,Spring Security 3.2.0和sockjs 0.3.4以及Tomcat 7.0.53