Categories
JavaScript Answers

How to add authentication with Socket.IO and JavaScript?

Spread the love

To add authentication with Socket.IO and JavaScript, we call send to get the key from client side and receive it on server side.

For instance, we write

const jwt = require("jsonwebtoken");
//...
app.post("/login", (req, res) => {
  const profile = {
    first_name: "John",
    last_name: "Doe",
    email: "john@doe.com",
    id: 123,
  };

  const token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60 * 5 });
  res.json({ token });
});

to add the /login endpoint.

Then we call jwt.sign to return am auth token with the profile data.

Then we write

const socketioJwt = require("socketio-jwt");
const sio = socketIo.listen(server);

sio.set(
  "authorization",
  socketioJwt.authorize({
    secret: jwtSecret,
    handshake: true,
  })
);

sio.sockets.on("connection", (socket) => {
  console.log(socket.handshake.decoded_token.email, "has joined");
});

to use the socketio-jwt package to add authentication to Socket.io.

We use it to add JWT authentication with secret set to jwtSecret.

And we listen to the connection event with handler that gets the decoded token’s email.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *