add test for unauthorized websocket usage

This commit is contained in:
Athou
2024-01-03 21:08:25 +01:00
parent 860aab7495
commit cf3100081e
2 changed files with 29 additions and 4 deletions

View File

@@ -24,11 +24,12 @@ public class WebSocketEndpoint extends Endpoint {
Long userId = (Long) config.getUserProperties().get(WebSocketConfigurator.SESSIONKEY_USERID);
if (userId == null) {
reject(session);
} else {
log.debug("created websocket session for user {}", userId);
sessions.add(userId, session);
return;
}
log.debug("created websocket session for user {}", userId);
sessions.add(userId, session);
session.addMessageHandler(String.class, message -> {
if ("ping".equals(message)) {
session.getAsyncRemote().sendText("pong");
@@ -47,7 +48,6 @@ public class WebSocketEndpoint extends Endpoint {
@Override
public void onClose(Session session, CloseReason reason) {
sessions.remove(session);
}
}

View File

@@ -14,6 +14,7 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.Endpoint;
@@ -22,6 +23,30 @@ import jakarta.websocket.Session;
class WebSocketIT extends BaseIT {
@Test
void sessionClosedIfNotLoggedIn() throws DeploymentException, IOException {
ClientEndpointConfig config = buildConfig("fake-session-id");
AtomicBoolean connected = new AtomicBoolean();
AtomicReference<CloseReason> closeReasonRef = new AtomicReference<>();
try (Session ignored = ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
@Override
public void onOpen(Session session, EndpointConfig config) {
connected.set(true);
}
@Override
public void onClose(Session session, CloseReason closeReason) {
closeReasonRef.set(closeReason);
}
}, config, URI.create(getWebSocketUrl()))) {
Awaitility.await().atMost(15, TimeUnit.SECONDS).untilTrue(connected);
Awaitility.await().atMost(15, TimeUnit.SECONDS).until(() -> closeReasonRef.get() != null);
Assertions.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY, closeReasonRef.get().getCloseCode());
}
}
@Test
void subscribeAndGetsNotified() throws DeploymentException, IOException {
String sessionId = login();