I've web & websocket server written in Spring framework. There is no authentication required by design but I want to identify each visitor unique. But as far as I understand, Spring has a built-in mechanism called JSESSIONID
(please correct me if I'm misunderstand this concept) to
I wrote a custom websocket handshake handler but every time after reconnect (close browser tab) I get new session identifier with request.servletRequest.session
(it seemed to me that this is JSESSIONID
?). At least value of JSESSIONID
doesn't change when I track cookies in my browser.
My goal is to make a websocket chat with no authentication required. I guess I need to get Principal
in the controllers that contains JSESSIONID
as the name. I've tried to make custom handshake handler but session identifier in ServletServerHttpRequest regenerates every time I reopen the browser's tab.
class CustomHandshakeHandler : DefaultHandshakeHandler() {
override fun determineUser(
request: ServerHttpRequest,
wsHandler: WebSocketHandler,
attributes: Map<String, Any>
): Principal? {
if (request is ServletServerHttpRequest) {
println(request.servletRequest.session.id) // expected the same session identifier on each request
}
val authorities = mutableListOf<SimpleGrantedAuthority>()
authorities.add(SimpleGrantedAuthority("ROLE_ANONYMOUS"))
return AnonymousAuthenticationToken("WebsocketConfiguration", "anonymous", authorities) // replace "anonymous" with session identifier
}
}
Here is websocket configuration:
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig : WebSocketMessageBrokerConfigurer {
override fun configureMessageBroker(registry: MessageBrokerRegistry) {
registry.enableSimpleBroker("/queue", "/topic")
registry.setApplicationDestinationPrefixes("/app")
}
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/ws")
.setAllowedOriginPatterns("*")
.setHandshakeHandler(CustomHandshakeHandler())
.withSockJS()
.setInterceptors(HttpSessionHandshakeInterceptor())
}
}
question from:
https://stackoverflow.com/questions/65642623/identify-unique-visitor-with-cookie-access-principal-from-websocket-message 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…