Security protection applied on http/https server and the mechanisms used regardless of the distribution you are using (e.g. express, feathers, total.js, etc) do not secure socket.io. This is a separate issue that we will look at in this article. We will focus on the 3 most known security mechanisms. In this article we focus on security protection based on local server side generated Token. Our project will be works both for browser, mobile and desktop clients.
Authorisation socket.io flow will be following:
– User has to login to server
– every request, both unauthorised and authorised is verified by security mechanisms
– in case of not authorised requests server forse closes socket of client – thank’s to this we reduce number of current connections
Structure our project:
/server.js – main server based on express.js – the structure is very easy:
Because we use environment variables then we will use dotenv module to automatically load defined variables from .env file.
In current project we will use and focus only on LOCAL_JWT_SECRET key
Whole socket.io logic is placed in separate file /modules/mainSocketLocalToken.js which is called from express.js server.
Two socket actions/events called as getUser and message are security protected.
getUser – fetches user by id
message – send broadcast message to all logged users
In order to security our socket.io communication we have to add a function JWT validating the correctness of our key (JWT token generated on server side). In this situation path of authorisation will be following:
– function JWT checks the correctness of our token (JWT token comes from local server) in every emitted message and connection
– socket.io applies defined process of authorisation (validation if user exists in our db)
Whole logic will be contained in /definitions/authorization.js
To implementation JWT validation we will apply jsonwebtoken npm module (read more)
Important: jsonwebtoken verify function is asynchronous – that’s why we will treat as promise function. Please pay attention also on socket.disconnect(true) – that is reposnsible to close socket for unauthorised users
The last thing is implimentation and the use of the verifyConnection function in methods that require protection against unauthorized access.
VERY IMPORTANT: PROTECT YOUR SECRET_KEY – it should be stored only on server side
Let’s make a test: when user is not logged and will try use function to broadcast function to send message to other user then he will receive error on Your side that is not authorised – in console log You will see also errors related with protection our functions on socket.io side.
Unauthenticated users:
And for authenticated users:
Source codes of project on GitHub under https://github.com/maxprog/socket.io-token-based-authentication