Performing token-based authentication
Now that we are able to perform basic authentication with Socket.IO, let's take a look at a token-based approach that handles authentication more securely, such as JSON Web Tokens, or JWT.
JSON Web Tokens are an URL-safe means of representing claims to be transferred between two parties. The claims in a JSON Web Token are encoded as a JSON object that is digitally signed using JSON Web Signature. With this approach, we can securely send a salted web token to the client to use on subsequent requests.
Getting ready
For this recipe, we will use the jsonwebtokennpm
package to create secure JSON Web Tokens. The package can be installed by running npm install jsonwebtoken –save
in your terminal.
How to do it…
To perform token-based authentication, follow these steps:
First, let's create our server and expose the events of Socket.IO to authenticate and receive a JSON Web Token. In this example, we will hardcode a profile to be associated with the JWT, but you would...