5

I'm trying to catch SessionDisconnectEvent event with listener:


    @Component
public class WebSocketDisconnectListener implements ApplicationListener {

    @Override
    @EventListener
    public void onApplicationEvent(SessionDisconnectEvent event) {
        Principal principal = event.getUser();
        logger.info("websocket disconnected {}, user {}", event, principal);
        if (principal != null) {
        }
    }
}

But the principal is always null. So I found that SessionDisconnectEvent has an event named sessionId, But how could I use the sessionId?

Where to get the session or principal?

Suraj Sakhare
  • 363
  • 1
  • 4
  • 12
disorderdev
  • 1,458
  • 1
  • 14
  • 28

2 Answers2

0

try like this.

public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        log.info("Disconnect event [sessionId: " + sha.getSessionId() + " : close status" + event.getCloseStatus() + "]");
    }
yagu
  • 177
  • 1
  • 9
0

I guess you maybe didn't enable Spring security with AuthenticationProvider. In that case, the system can't specify the session user who logon. On the other hand, user authentication handling is pain in websockets. I followed this topic and revised the solution to my authentication method with JWT token. I can reach my session user principal with your code.