5

Recent Version of Spring WebSocket works with SockJS and StompJS libraries. But i don't like to use theme in my application. So how to create Spring WebSocket application with HTML5 WebSocket API and integrate our application with Spring Security?

1 Answer 1

4

I could not find any good example on how to configure spring websocket without sockjs but i found some helpful documentation in spring documentation site and i like to share that. Well, How to Create Spring WebSocket Application With HTML5 WebSocket API?

First: Create a Class that extends TextWebSocketHandler or BinaryWebSocketHandler and Annotate it with @Component annotation and Override its appropriate method.This Class works like handler methods in controllers.

@Component
public class SimpleWebSocketHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, 
            TextMessage message) throws Exception {
        // Sends back response to client.
        session.sendMessage(new TextMessage("Connection is all right."));
    }
}

Second: Create a Configuration Class that implements WebSocketConfigurer and Annotate it with @Configuration and @EnableWebSocket annoations and Override its appropriate method.This Class uses Handler Class that we created already.

@Configuration
@EnableWebSocket
public class WebSocketConfigurations implements WebSocketConfigurer {
    @Autowired
    private SimpleWebSocketHandler simpleWebSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // Regsiters a handler for related endpoint.
        registry.addHandler(simpleWebSocketHandler, "/chat");
    }
}

Third: Add all your WebSokcet Endpoints to your Spring Security Configuration.

httpSecurity.authorizeRequests()
    .antMatchers("/chat").permitAll();

Fourth: We create a new javascript WebSocket objet with appropriate URL.

// Create WebSocket Object.
var ws = new WebSocket("ws://localhost:8080/chat");

// Runs when connecion is estabilished.
ws.onopen = function () {
    // Sends request to server with string value.
    ws.send("webSocket");
};

// Runs when response is ready.
// Use event to get response value.
ws.onmessage = function (event) {

};

Note: WebSocket URLs Format: ws://domain:port/endpoint

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, but I can use spring websocket only after registry.addHandler(simpleWebSocketHandler, "/chat").setAllowedOrigins("*"); otherwise I get 302 or 403 errors. Spring Security Configuration does not really helps in my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.