Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

java - Identify unique visitor with cookie & access principal from websocket message

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...