ioreskovic
ioreskovic

Reputation: 5699

How to deny WebSocket connections when no sub-protocol is specified

I'm trying to allow only specific sub-protocols when client tries to establish WebSocket connection.

My understanding is I need to define a handler which supports specific sub-protocols.

public class MyWebSocketHandler implements WebSocketHandler {
    private static final List<String> subProtocols = Collections.unmodifiableList(Arrays.asList(
        "MySubProtocol_v0",
        "MySubProtocol_v1"
    ));

    @Override
    public List<String> getSubProtocols() {
        return subProtocols;
    }

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        return session.send(session.receive()
            .log((String) null, Level.INFO, true)
            .map(msg -> session.textMessage("Echo: " + msg.getPayloadAsText())));
    }
}

Indeed, when I try to connect and negotiate any of those specified sub-protocols, it passes:

15:11:11 command: /connect ws://localhost:8080/ingest MySubProtocol_v1
15:11:11 system:  Connecting to ws://localhost:8080/ingest
                  Accepted protocols: MySubProtocol_v1
15:11:12 system:  Connection established.
                  Selected protocol: MySubProtocol_v1

When I try to connect and negotiate unsupported protocol, connection is not established:

15:14:10 command: /connect ws://localhost:8080/ingest MySubProtocol_v2
15:14:10 system:  Connecting to ws://localhost:8080/ingest
                  Accepted protocols: MySubProtocol_v2
15:14:10 error:   WebSocket error.
15:14:10 system:  Connection closed.
Close status:     1006 (Abnormal Closure)

However, when I do not try to negotiate sub-protocol, the connection IS established.

15:17:23 command: /connect ws://localhost:8080/ingest
15:17:23 system:  Connecting to ws://localhost:8080/ingest
                  No protocol negotiation.
15:17:23 system:  Connection established.

What do I need to do to force specifying correct sub-protocol?

Upvotes: 2

Views: 681

Answers (1)

Marcin Bukowiecki
Marcin Bukowiecki

Reputation: 410

You can obtain the sub-protocol information from HandshakeInfo object: session.getHandshakeInfo(). HandshakeInfo instance contains the sub-protocol which was used at the negotiation.

Upvotes: 1

Related Questions