1

I am using websockets without Stomp. What is the correct way to decide to whom USer WebSocketSession belongs to?

In my WsConfig i use:

@Configuration
@EnableWebSocket
public class WebSocketServerConfiguration implements WebSocketConfigurer {

    protected final CustomWebSocketHandler webSocketHandler;

    @Autowired
    public WebSocketServerConfiguration(CustomWebSocketHandler webSocketHandler) {
        this.webSocketHandler = webSocketHandler;

}
    @SuppressWarnings("NullableProblems")
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketHandler, "/ws")
                .addInterceptors();
    }
}

my WsHandler is currently empty:

@Service
public class SplitBillWebSocketHandler extends TextWebSocketHandler {


    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
         
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
             //determine User for session
              User user = determineUser(session);
             sessionStorage.add(user.getName(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage jsonTextMessage) throws Exception {

    }
}

What is the way to determine the user? Or what is the best practice to do this?

Do I need to pass some parameter to websocket URL from client ( which isn't standard as far as I am aware ), or how to identify the session?

Thanks for help!

Darlyn
  • 4,715
  • 12
  • 40
  • 90
  • Take a look at [WebSocketSession#getPrincipal](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/socket/WebSocketSession.html#getPrincipal--). That is containing the principal associated with the current authentication. – Ken S Aug 15 '20 at 06:03
  • You could determine the user, based on the unique sessionId or if the username is going to be unique you could add that as well. Which one is your use-case ? – srinivas kumar Aug 15 '20 at 08:06
  • yes, however how do i set the principal of the session? How is it set in the connection? I cannot find anything about it – Darlyn Aug 15 '20 at 11:25
  • The websocket does not support sending Authorization header, and during the handshake (upgrade request) no info is sent. – Darlyn Aug 15 '20 at 12:43
  • If the user is logged in before the handshake, principal will be in http session. https://stackoverflow.com/questions/28567146/how-to-set-a-principal-within-a-handshakeinterceptor. Here you can do request.getSession and then principal from http session – Kavithakaran Kanapathippillai Aug 15 '20 at 18:05

0 Answers0