1

I am working on implementing WebSocket integration tests. I cannot get the mock user to be passed to the client.

@WithMockUser(value = "user", roles = "USER")
void test() throws ExecutionException, InterruptedException, TimeoutException {
    webSocketStompClient = new WebSocketStompClient(
        new SockJsClient(List.of(new WebSocketTransport(new StandardWebSocketClient())))
    );
    
    StompSession session = webSocketStompClient
        .connect(String.format("ws://localhost:%d/ws", port),
            new StompSessionHandlerAdapter() {
            }
        )
        .get(1, SECONDS);
}

Unfortunately, I receive the following error:

TopicInterceptorIT > test() FAILED
    java.util.concurrent.ExecutionException at TopicInterceptorIT.java:57
        Caused by: org.springframework.messaging.simp.stomp.ConnectionLostException at DefaultStompSession.java:518
2022-01-17 12:04:19.415  WARN [,,,] 44518 --- [   XNIO-1 I/O-9] w.s.h.ExceptionWebSocketHandlerDecorator : Unhandled exception after connection closed for ExceptionWebSocketHandlerDecorator [delegate=LoggingWebSocketHandlerDecorator [delegate=WebSocketMsgEnhancer [delegate=SubProtocolWebSocketHandler[StompSubProtocolHandler[v10.stomp, v11.stomp, v12.stomp]]]]]
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied

Do I have to manually create the access token and inject it into the request headers? Or is there an approach similar to the @WithMockUser over MockMvc familiar when testing REST endpoints?

Alexandre Cassagne
  • 2,384
  • 23
  • 40
  • '@WithMockUser' is only for simpler role based security. Maybe you need to create a '@TestConfiguration' class where you can create your 'logged user'. Check this: https://stackoverflow.com/questions/15203485/spring-test-security-how-to-mock-authentication – canillas Jan 17 '22 at 12:33
  • @canillas thank you, but for now, I am ok with a simple mock user. However, the spring security Principal is not loaded using the above, naïve approach. The user only needs to have the role = "USER", but the connection is rejected. Do you understand why/how to fix that? – Alexandre Cassagne Jan 17 '22 at 13:47

0 Answers0