简体   繁体   中英

Get Websocket session data in Spring when handing STOMP SEND

Spring Websocket tutorial tells that if I like to handle STOMP SEND command, I shall use ( http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html )

@Controller
public class GreetingController {

    @MessageMapping("/greeting") {
    public String handle(String greeting) {
    return "[" + getTimestamp() + ": " + greeting;
    }

}

I need however also know which Websocket Session was sending this, in order to do the check like

if (sessionIsAllowedToDoThings(sessionData))   {...}

How I can therefore get Websocket Session data for this example?

Well, you can obtain websocket's session id (and other fields) by adding org.springframework.messaging.simp.stomp.StompHeaderAccessor parameter to your handle(String) method: handle(String, StompHeaderAccessor) .

If you want to access your real JSESSIONID attribute, you have to create an implementation of org.springframework.web.socket.server.HandshakeInterceptor like so (it is written in Kotlin):

class HttpHandshakeInterceptor : HandshakeInterceptor {

    companion object {
        const val ATTRIBUTE_SESSION_ID = "sessionId"
    }

    override fun beforeHandshake(request: ServerHttpRequest, response: ServerHttpResponse, wsHandler: WebSocketHandler, attributes: MutableMap<String, Any>): Boolean {
        attributes[ATTRIBUTE_SESSION_ID] = (request as ServletServerHttpRequest).servletRequest.session.id
        return true
    }

    override fun afterHandshake(request: ServerHttpRequest, response: ServerHttpResponse, wsHandler: WebSocketHandler, exception: Exception?) {}
}

and register it wihtin your org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer like so:

override fun registerStompEndpoints(registry: StompEndpointRegistry) {
    registry.addEndpoint("/endpoint").addInterceptors(httpHandshakeInterceptor)
}

The main idea here is that you intercept the initial handshake and store real session id within the websocket attributes. The attributes are available through StompHeaderAccessor you passed to your handle(String, StompHeaderAccessor) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM