Search code examples
springspring-securityspring-websocketjetty-9java-websocket

How to authenticate Jetty websocket client for spring websocket (JSR-356)


We have Spring websocket [STOMP and JSR] at server side and Jetty websocket client to communicate with server. Authentication works fine from browser as we authenticate user on login, we have sockjs STOMP at browser side, but we need authentication at Jetty websocket client also.

How to do that? Any other option?


Solution

  • Specify Basic authentication in spring auth configuration

    <security:http auto-config="true" pattern="/websocket" use-expressions="true" entry-point-ref="ajaxAwareAuthenticationEntryPoint" disable-url-rewriting="false">
        <security:intercept-url pattern="/**" access="isAuthenticated()" />
        <security:http-basic/>
    </security:http>
    

    Jetty websocket client SSL configuration along with user authentication

    URI serverURI = new URI("wss://domain:port/websocket");
    ClassLoader classLoader = getClass().getClassLoader();
    URL url = classLoader.getResource("resources/domain.jks");
    SslContextFactory sslContextFactory = new SslContextFactory();  
    Resource keyStoreResource = Resource.newResource(url);
    sslContextFactory.setKeyStoreResource(keyStoreResource);
    sslContextFactory.setKeyStorePassword("Keystore Password");
    sslContextFactory.setKeyManagerPassword("Keystore Password");   
    WebSocketClient webSocketClient = new WebSocketClient(sslContextFactory);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    request.setSubProtocols("xsCrossfire");
    String basicAuthHeader = HttpBasicAuthHeader.generateBasicAuthHeader("username", "password");
    request.setHeader("Authorization", "Basic " + basicAuthHeader);
    webSocketClient.start();
    // Websocket class (@WebSocket annotated)
    SecureClientSocket socket = new SecureClientSocket();
    final Future<Session> connect = webSocketClient.connect(socket, serverURI, request);