Authenticated websocket connection with Spring Boot and ReactJS
17 May 2018
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 from adding proper dependency in pom.xml on backend side. In my case it 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
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
Unfortunelty 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 depedencies, one for sockJs and second for webstomp of course.
And we are 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 few vending machines.
Every time machine sold a product data are send to our server and then transaction is
validated and eventualy inserted to database. In the end I’m sending event
UpdateDashboardRequestEvent to update dashboard.