🔐 Authenticated websockets in Spring Boot and ReactJS
Published on•
Last updated on
Websockets are an easy way to update data on clients side without making request to server where there is no new data.
It gives “wow effect” for clients and lower server costs for you.
Server side - Spring Framework
We will start from adding proper dependency in pom.xml on backend side. In my case it the latest stable version was 2.0.2.RELEASE.
Basic websockets configuration in Spring is easy as copy-paste configuration files and handle connection on client side.
Create new configuration class annotated with @Configuration and @EnableWebSocketMessageBroker and extend it with
AbstractWebSocketMessageBrokerConfigurer.
Remember to provide TaskScheduler which is required to sending messages.
In above example I also configured CORS by using list of allowed origins from *.yml configuration.
Support for websocket authentication
Unfortunately as far as I know Spring websockets does not support authentication, so we need to implement it on our own.
I came up with very simple idea, I’m authenticating user on SessionSubscribeEvent.
Now we are ready to send data to connected clients! In my application I’m using application events
to send updates with ease to connected companies from any place in code.
In my case I’m sending update to dashboard page on every new transaction for company.
Every user subscribe his company message channel and get update on every transaction or alert if occurred.
Client side - ReactJS
On client side I’m using two additional dependencies, one for SockJS and second for webstomp of course.
Done! 🌱 Below is an example how it looks like in my application.
In terminal, we see logs from the server for test demo company with a vending machines.
Every time machine sold a product data are sent to our server, and then transaction is
validated and eventually inserted to database. In the end I’m sending event
UpdateDashboardRequestEvent to update the dashboard with WebSockets.