Top Description Inners Fields Constructors Methods
org.springframework.web.socket.sockjs.support

public abstract Class AbstractSockJsService

extends Object
implements SockJsService, CorsConfigurationSource
Class Inheritance
All Implemented Interfaces
org.springframework.web.cors.CorsConfigurationSource, org.springframework.web.socket.sockjs.SockJsService
Known Direct Subclasses
org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService
Imports
java.io.IOException, java.nio.charset.StandardCharsets, java.util.ArrayList, .Arrays, .Collection, .Collections, .LinkedHashSet, .List, .Random, java.util.concurrent.TimeUnit, jakarta.servlet.http.HttpServletRequest, org.apache.commons.logging.Log, .LogFactory, org.springframework.core.log.LogFormatUtils, org.springframework.http.HttpHeaders, .HttpMethod, .HttpStatus, .InvalidMediaTypeException, .MediaType, org.springframework.http.server.ServerHttpRequest, .ServerHttpResponse, org.springframework.lang.Nullable, org.springframework.scheduling.TaskScheduler, org.springframework.util.Assert, .CollectionUtils, .DigestUtils, .ObjectUtils, .StringUtils, org.springframework.web.cors.CorsConfiguration, .CorsConfigurationSource, org.springframework.web.socket.WebSocketHandler, org.springframework.web.socket.sockjs.SockJsException, .SockJsService, org.springframework.web.util.WebUtils

An abstract base class for SockJsService implementations that provides SockJS path resolution and handling of static SockJS requests (e.g. "/info", "/iframe.html", etc). Sub-classes must handle session URLs (i.e. transport-specific requests).

By default, only same origin requests are allowed. Use setAllowedOrigins to specify a list of allowed origins (a list containing "*" will allow all origins).

Authors
Rossen Stoyanchev, Sebastien Deleuze
Since
4.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
private class
private static interface

Field Summary

Modifier and TypeField and Description
private String
protected final CorsConfiguration
private long
private long
private int
private final AbstractSockJsService.SockJsRequestHandler
private final AbstractSockJsService.SockJsRequestHandler
protected final Log
private String
private static final long
private static final Random
private boolean
private int
private boolean
private final TaskScheduler
private boolean
private static final String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
protected void
protected boolean
checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)

public Collection<String>
getAllowedOriginPatterns()

Return configured origin patterns.

public Collection<String>
getAllowedOrigins()

Return the configured allowed origins.

public CorsConfiguration
public long
getDisconnectDelay()

Return the amount of time in milliseconds before a client is considered disconnected.

public long
getHeartbeatTime()

Return the amount of time in milliseconds when the server has not sent any messages.

public int
getHttpMessageCacheSize()

Return the size of the HTTP message cache.

public String
getName()

Return the unique name associated with this service.

public String
getSockJsClientLibraryUrl()

Return he URL to the SockJS JavaScript client library.

public int
getStreamBytesLimit()

Return the minimum number of bytes that can be sent over a single HTTP streaming request before it will be closed.

public TaskScheduler
getTaskScheduler()

A scheduler instance to use for scheduling heart-beat messages.

protected abstract void
handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler)

Handle request for raw WebSocket communication, i.e. without any SockJS message framing.

public final void
handleRequest(ServerHttpRequest
the current request
request
,
ServerHttpResponse
the current response
response
,
String
the remainder of the path within the SockJS service prefix
sockJsPath
,
WebSocketHandler
the handler that will exchange messages with the SockJS client
wsHandler
)

Implements org.springframework.web.socket.sockjs.SockJsService.handleRequest.

This method determines the SockJS path and handles SockJS static URLs.

protected abstract void
handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, String sessionId, String transport)

Handle a SockJS session URL (i.e. transport-specific request).

private static CorsConfiguration
public boolean
isSessionCookieNeeded()

Return whether the JSESSIONID cookie is required for the application to function.

public boolean
isWebSocketEnabled()

Return whether WebSocket transport is enabled.

protected void
public void
setAllowedOriginPatterns(Collection<String> allowedOriginPatterns)

Alternative to setAllowedOrigins(Collection) that supports more flexible patterns for specifying the origins for which cross-origin requests are allowed from a browser.

public void
setAllowedOrigins(Collection<String> allowedOrigins)

Set the origins for which cross-origin requests are allowed from a browser.

public void
setDisconnectDelay(long disconnectDelay)

The amount of time in milliseconds before a client is considered disconnected after not having a receiving connection, i.e. an active connection over which the server can send data to the client.

public void
setHeartbeatTime(long heartbeatTime)

Specify the amount of time in milliseconds when the server has not sent any messages and after which the server should send a heartbeat frame to the client in order to keep the connection from breaking.

public void
setHttpMessageCacheSize(int httpMessageCacheSize)

The number of server-to-client messages that a session can cache while waiting for the next HTTP polling request from the client.

public void
setName(String name)

Set a unique name for this service (mainly for logging purposes).

public void
setSessionCookieNeeded(boolean sessionCookieNeeded)

The SockJS protocol requires a server to respond to an initial "/info" request from clients with a "cookie_needed" boolean property that indicates whether the use of a JSESSIONID cookie is required for the application to function correctly, e.g. for load balancing or in Java Servlet containers for the use of an HTTP session.

public void
setSockJsClientLibraryUrl(String clientLibraryUrl)

Transports with no native cross-domain communication (e.g. "eventsource", "htmlfile") must get a simple page from the "foreign" domain in an invisible iframe so that code in the iframe can run from a domain local to the SockJS server.

public void
setStreamBytesLimit(int streamBytesLimit)

Streaming transports save responses on the client side and don't free memory used by delivered messages.

public void
setSuppressCors(boolean suppressCors)

This option can be used to disable automatic addition of CORS headers for SockJS requests.

public void
setWebSocketEnabled(boolean webSocketEnabled)

Some load balancers do not support WebSocket.

public boolean
shouldSuppressCors()

Return if automatic addition of CORS headers has been disabled.

private boolean
validatePath(ServerHttpRequest request)

Ensure the path does not contain a file extension, either in the filename (e.g. "/jsonp.bat") or possibly after path parameters ("/jsonp;Setup.bat") which could be used for RFD exploits.

protected boolean
validateRequest(String serverId, String sessionId, String transport)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

clientLibraryUrlback to summary
private String clientLibraryUrl
corsConfigurationback to summary
protected final CorsConfiguration corsConfiguration
disconnectDelayback to summary
private long disconnectDelay
heartbeatTimeback to summary
private long heartbeatTime
httpMessageCacheSizeback to summary
private int httpMessageCacheSize
iframeHandlerback to summary
private final AbstractSockJsService.SockJsRequestHandler iframeHandler
infoHandlerback to summary
private final AbstractSockJsService.SockJsRequestHandler infoHandler
loggerback to summary
protected final Log logger
nameback to summary
private String name
ONE_YEARback to summary
private static final long ONE_YEAR
randomback to summary
private static final Random random
sessionCookieNeededback to summary
private boolean sessionCookieNeeded
streamBytesLimitback to summary
private int streamBytesLimit
suppressCorsback to summary
private boolean suppressCors
taskSchedulerback to summary
private final TaskScheduler taskScheduler
webSocketEnabledback to summary
private boolean webSocketEnabled
XFRAME_OPTIONS_HEADERback to summary
private static final String XFRAME_OPTIONS_HEADER

Constructor Detail

AbstractSockJsServiceback to summary
public AbstractSockJsService(TaskScheduler scheduler)

Method Detail

addCacheHeadersback to summary
protected void addCacheHeaders(ServerHttpResponse response)
addNoCacheHeadersback to summary
protected void addNoCacheHeaders(ServerHttpResponse response)
checkOriginback to summary
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) throws IOException
getAllowedOriginPatternsback to summary
public Collection<String> getAllowedOriginPatterns()

Return configured origin patterns.

Annotations
@SuppressWarnings:ConstantConditions
Since
5.3.2
getAllowedOriginsback to summary
public Collection<String> getAllowedOrigins()

Return the configured allowed origins.

Annotations
@SuppressWarnings:ConstantConditions
Since
4.1.2
getCorsConfigurationback to summary
public CorsConfiguration getCorsConfiguration(HttpServletRequest request)

Implements org.springframework.web.cors.CorsConfigurationSource.getCorsConfiguration.

Doc from org.springframework.web.cors.CorsConfigurationSource.getCorsConfiguration.

Return a CorsConfiguration based on the incoming request.

Returns:CorsConfiguration

the associated CorsConfiguration, or null if none

Annotations
@Override
@Nullable
getDisconnectDelayback to summary
public long getDisconnectDelay()

Return the amount of time in milliseconds before a client is considered disconnected.

getHeartbeatTimeback to summary
public long getHeartbeatTime()

Return the amount of time in milliseconds when the server has not sent any messages.

getHttpMessageCacheSizeback to summary
public int getHttpMessageCacheSize()

Return the size of the HTTP message cache.

getNameback to summary
public String getName()

Return the unique name associated with this service.

getSockJsClientLibraryUrlback to summary
public String getSockJsClientLibraryUrl()

Return he URL to the SockJS JavaScript client library.

getStreamBytesLimitback to summary
public int getStreamBytesLimit()

Return the minimum number of bytes that can be sent over a single HTTP streaming request before it will be closed.

getTaskSchedulerback to summary
public TaskScheduler getTaskScheduler()

A scheduler instance to use for scheduling heart-beat messages.

handleRawWebSocketRequestback to summary
protected abstract void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler) throws IOException

Handle request for raw WebSocket communication, i.e. without any SockJS message framing.

handleRequestback to summary
public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, String sockJsPath, WebSocketHandler wsHandler) throws SockJsException

Implements org.springframework.web.socket.sockjs.SockJsService.handleRequest.

This method determines the SockJS path and handles SockJS static URLs. Session URLs and raw WebSocket requests are delegated to abstract methods.

Parameters
request:ServerHttpRequest

Doc from org.springframework.web.socket.sockjs.SockJsService.handleRequest.

the current request

response:ServerHttpResponse

Doc from org.springframework.web.socket.sockjs.SockJsService.handleRequest.

the current response

sockJsPath:String

Doc from org.springframework.web.socket.sockjs.SockJsService.handleRequest.

the remainder of the path within the SockJS service prefix

wsHandler:WebSocketHandler

Doc from org.springframework.web.socket.sockjs.SockJsService.handleRequest.

the handler that will exchange messages with the SockJS client

Annotations
@Override
Exceptions
SockJsException:

Doc from org.springframework.web.socket.sockjs.SockJsService.handleRequest.

raised when request processing fails; generally, failed attempts to send messages to clients automatically close the SockJS session and raise SockJsTransportFailureException; failed attempts to read messages from clients do not automatically close the session and may result in SockJsMessageDeliveryException or SockJsException; exceptions from the WebSocketHandler can be handled internally or through ExceptionWebSocketHandlerDecorator or some alternative decorator. The former is automatically added when using org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler.

handleTransportRequestback to summary
protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, String sessionId, String transport) throws SockJsException

Handle a SockJS session URL (i.e. transport-specific request).

initCorsConfigurationback to summary
private static CorsConfiguration initCorsConfiguration()
isSessionCookieNeededback to summary
public boolean isSessionCookieNeeded()

Return whether the JSESSIONID cookie is required for the application to function.

isWebSocketEnabledback to summary
public boolean isWebSocketEnabled()

Return whether WebSocket transport is enabled.

sendMethodNotAllowedback to summary
protected void sendMethodNotAllowed(ServerHttpResponse response, HttpMethod... httpMethods)
setAllowedOriginPatternsback to summary
public void setAllowedOriginPatterns(Collection<String> allowedOriginPatterns)

Alternative to setAllowedOrigins(Collection) that supports more flexible patterns for specifying the origins for which cross-origin requests are allowed from a browser. Please, refer to CorsConfiguration#setAllowedOriginPatterns(List) for format details and other considerations.

By default this is not set.

Since
5.2.3
setAllowedOriginsback to summary
public void setAllowedOrigins(Collection<String> allowedOrigins)

Set the origins for which cross-origin requests are allowed from a browser. Please, refer to CorsConfiguration#setAllowedOrigins(List) for format details and considerations, and keep in mind that the CORS spec does not allow use of "*" with allowCredentials=true. For more flexible origin patterns use setAllowedOriginPatterns instead.

By default, no origins are allowed. When allowedOriginPatterns is also set, then that takes precedence over this property.

Note when SockJS is enabled and origins are restricted, transport types that do not allow to check request origin (Iframe based transports) are disabled. As a consequence, IE 6 to 9 are not supported when origins are restricted.

Since
4.1.2
See Also
setAllowedOriginPatterns(Collection), RFC 6454: The Web Origin Concept, SockJS supported transports by browser
setDisconnectDelayback to summary
public void setDisconnectDelay(long disconnectDelay)

The amount of time in milliseconds before a client is considered disconnected after not having a receiving connection, i.e. an active connection over which the server can send data to the client.

The default value is 5000.

setHeartbeatTimeback to summary
public void setHeartbeatTime(long heartbeatTime)

Specify the amount of time in milliseconds when the server has not sent any messages and after which the server should send a heartbeat frame to the client in order to keep the connection from breaking.

The default value is 25,000 (25 seconds).

setHttpMessageCacheSizeback to summary
public void setHttpMessageCacheSize(int httpMessageCacheSize)

The number of server-to-client messages that a session can cache while waiting for the next HTTP polling request from the client. All HTTP transports use this property since even streaming transports recycle HTTP requests periodically.

The amount of time between HTTP requests should be relatively brief and will not exceed the allows disconnect delay (see setDisconnectDelay(long)); 5 seconds by default.

The default size is 100.

setNameback to summary
public void setName(String name)

Set a unique name for this service (mainly for logging purposes).

setSessionCookieNeededback to summary
public void setSessionCookieNeeded(boolean sessionCookieNeeded)

The SockJS protocol requires a server to respond to an initial "/info" request from clients with a "cookie_needed" boolean property that indicates whether the use of a JSESSIONID cookie is required for the application to function correctly, e.g. for load balancing or in Java Servlet containers for the use of an HTTP session.

This is especially important for IE 8,9 that support XDomainRequest -- a modified AJAX/XHR -- that can do requests across domains but does not send any cookies. In those cases, the SockJS client prefers the "iframe-htmlfile" transport over "xdr-streaming" in order to be able to send cookies.

The SockJS protocol also expects a SockJS service to echo back the JSESSIONID cookie when this property is set to true. However, when running in a Servlet container this is not necessary since the container takes care of it.

The default value is "true" to maximize the chance for applications to work correctly in IE 8,9 with support for cookies (and the JSESSIONID cookie in particular). However, an application can choose to set this to "false" if the use of cookies (and HTTP session) is not required.

setSockJsClientLibraryUrlback to summary
public void setSockJsClientLibraryUrl(String clientLibraryUrl)

Transports with no native cross-domain communication (e.g. "eventsource", "htmlfile") must get a simple page from the "foreign" domain in an invisible iframe so that code in the iframe can run from a domain local to the SockJS server. Since the iframe needs to load the SockJS JavaScript client library, this property allows specifying where to load it from.

By default this is set to point to "https://cdn.jsdelivr.net/sockjs/1.0.0/sockjs.min.js". However, it can also be set to point to a URL served by the application.

Note that it's possible to specify a relative URL in which case the URL must be relative to the iframe URL. For example assuming a SockJS endpoint mapped to "/sockjs", and resulting iframe URL "/sockjs/iframe.html", then the relative URL must start with "../../" to traverse up to the location above the SockJS mapping. In case of a prefix-based Servlet mapping one more traversals may be needed.

setStreamBytesLimitback to summary
public void setStreamBytesLimit(int streamBytesLimit)

Streaming transports save responses on the client side and don't free memory used by delivered messages. Such transports need to recycle the connection once in a while. This property sets a minimum number of bytes that can be sent over a single HTTP streaming request before it will be closed. After that client will open a new request. Setting this value to one effectively disables streaming and will make streaming transports to behave like polling transports.

The default value is 128K (i.e. 128 * 1024).

setSuppressCorsback to summary
public void setSuppressCors(boolean suppressCors)

This option can be used to disable automatic addition of CORS headers for SockJS requests.

The default value is "false".

Since
4.1.2
setWebSocketEnabledback to summary
public void setWebSocketEnabled(boolean webSocketEnabled)

Some load balancers do not support WebSocket. This option can be used to disable the WebSocket transport on the server side.

The default value is "true".

shouldSuppressCorsback to summary
public boolean shouldSuppressCors()

Return if automatic addition of CORS headers has been disabled.

Since
4.1.2
See Also
setSuppressCors
validatePathback to summary
private boolean validatePath(ServerHttpRequest request)

Ensure the path does not contain a file extension, either in the filename (e.g. "/jsonp.bat") or possibly after path parameters ("/jsonp;Setup.bat") which could be used for RFD exploits.

Since the last part of the path is expected to be a transport type, the presence of an extension would not work. All we need to do is check if there are any path parameters, which would have been removed from the SockJS path during request mapping, and if found reject the request.

validateRequestback to summary
protected boolean validateRequest(String serverId, String sessionId, String transport)
org.springframework.web.socket.sockjs.support back to summary

private Class AbstractSockJsService.IframeHandler

extends Object
implements SockJsRequestHandler
Class Inheritance
  • java.lang.Object
  • org.springframework.web.socket.sockjs.support.AbstractSockJsService.IframeHandler
All Implemented Interfaces
org.springframework.web.socket.sockjs.support.AbstractSockJsService.SockJsRequestHandler

Field Summary

Modifier and TypeField and Description
private static final String

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

IFRAME_CONTENTback to summary
private static final String IFRAME_CONTENT

Constructor Detail

IframeHandlerback to summary
private IframeHandler()

Method Detail

handleback to summary
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException

Implements org.springframework.web.socket.sockjs.support.AbstractSockJsService.SockJsRequestHandler.handle.

Annotations
@Override
org.springframework.web.socket.sockjs.support back to summary

private Class AbstractSockJsService.InfoHandler

extends Object
implements SockJsRequestHandler
Class Inheritance
  • java.lang.Object
  • org.springframework.web.socket.sockjs.support.AbstractSockJsService.InfoHandler
All Implemented Interfaces
org.springframework.web.socket.sockjs.support.AbstractSockJsService.SockJsRequestHandler

Field Summary

Modifier and TypeField and Description
private static final String

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

INFO_CONTENTback to summary
private static final String INFO_CONTENT

Constructor Detail

InfoHandlerback to summary
private InfoHandler()

Method Detail

handleback to summary
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException

Implements org.springframework.web.socket.sockjs.support.AbstractSockJsService.SockJsRequestHandler.handle.

Annotations
@Override
org.springframework.web.socket.sockjs.support back to summary

private Interface AbstractSockJsService.SockJsRequestHandler

Known Direct Implementers
org.springframework.web.socket.sockjs.support.AbstractSockJsService.InfoHandler, org.springframework.web.socket.sockjs.support.AbstractSockJsService.IframeHandler

Method Summary

Modifier and TypeMethod and Description
public void

Method Detail

handleback to summary
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException