Currently I have a working solution with following components:
- Webserver with custom application
- Openresty with lua
- Keycloak
This allows me to authenticate using keycloak.
Because my webserver also exposes a websocket host, I would like to authenticate these websockets as well. Does anyone have an example (both the nginx file as the lua file) available to authenticate websocket connections using openresty? I've had a look at https://github.com/openresty/lua-resty-websocket but can't seem to find where to plugin in the authentication part.
An example client application to test this would be great as well!
I've figured it out myself. Posting my solution here to help others achieving the same.
I have following code snippets:
Openresty configuration
only for websocket, should be place inside the server section:
lua_acces.lua
This allows websocket connections only when they have a valid token retrieved from the keycloak service.
At the end, the resty user is filled in to pass on the authenticated user to the backend application.
Example Java client application
Get keycloak token
Websocket
This snippet only contains the function I call to setup the websocket connection. You still have to instantiate the _keycloakConnection object and in my case I have a general _session field to keep reuse the session each time I need it.
WebsocketEventHandler
A consumer is injected in this class to consume the messages in another class
Sending messages
When the _session is created you can use following line to send data:
These snippets are all a small part of my whole solution. I might have missed something. If somebody has a question or this is not working in your case, please reach out and I'll provide more information.