Categories
JavaScript Answers

How to authenticate socket.io connections using JWT?

Sometimes, we want to authenticate socket.io connections using JWT.

In this article, we’ll look at how to authenticate socket.io connections using JWT.

How to authenticate socket.io connections using JWT?

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.

For instance, we write

const {
  token
} = sessionStorage;
const socket = io.connect('http://localhost:3000', {
  query: {
    token
  }
});

to call io.connect to connect to the server.

We set the query.token property to send the auth token.

Then on the server, we write

const io = require('socket.io')();
const jwt = require('jsonwebtoken');

io.use((socket, next) => {
    if (socket.handshake?.query?.token) {
      jwt.verify(socket.handshake?.query?.token, 'SECRET_KEY', (err, decoded) => {
        if (err) {
          return next(new Error('Authentication error'));
        }
        socket.decoded = decoded;
        next();
      });
    } else {
      next(new Error('Authentication error'));
    }
  })
  .on('connection', (socket) => {
    socket.on('message', (message) => {
      io.emit('message', message);
    });
  });

to get the token with socket.handshake?.query?.token.

If it’s present, we check it with the jwt.verify method from the jsonwebtoken package against the private SECRET_KEY.

If auth is successful, err is null. And we call next with nothing.

Otherwise, we throw an error if the token isn’t present or when err is set.

Next, we call on with 'connection' to emit a message when connection succeeds.

Conclusion

To authenticate socket.io connections using JWT, we send the token with the socket.io client.

And then on the server, we check the token.

Categories
JavaScript Answers

How to add basic HTTP authentication with Node and Express 4?

Sometimes, we want to add basic HTTP authentication with Node and Express 4.

In this article, we’ll look at how to add basic HTTP authentication with Node and Express 4.

How to add basic HTTP authentication with Node and Express 4?

To add basic HTTP authentication with Node and Express 4, we can create our own middleware.

For instance, we write

app.use((req, res, next) => {
  const auth = {
    login: 'yourlogin',
    password: 'yourpassword'
  }
  const [, b64auth = ''] = (req.headers.authorization || '').split(' ')
  const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')
  if (login && password && login === auth.login && password === auth.password) {
    return next()
  }
  res.set('WWW-Authenticate', 'Basic realm="401"')
  res.status(401).send('Authentication required.')
})

to call app.use with a callback that checks if username 'yourlogin' and password 'password' received.

We check the username and password with

const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')

and

login && password && login === auth.login && password === auth.password

Then we call next to call the next middleware that we call when authentication succeeds.

Otherwise, we call res.set and res.status to return a 401 response.

Conclusion

To add basic HTTP authentication with Node and Express 4, we can create our own middleware.

Categories
JavaScript Answers

How to populate nested array in Mongoose?

Sometimes, we want to populate nested array in Mongoose.

In this article, we’ll look at how to populate nested array in Mongoose.

How to populate nested array in Mongoose?

To populate nested array in Mongoose, we can use the populate method.

For instance, we write

Project.find(query)
  .populate({
    path: 'pages',
    populate: {
      path: 'components',
      model: 'Component'
    }
  })
  .exec((err, docs) => {});

to call populate with an object with the array property we want to populate in the docs result.

We populate pages with the components entries in the returned Project entries.

docs has the returned result with the nested array results inside each entry.

Conclusion

To populate nested array in Mongoose, we can use the populate method.

Categories
JavaScript Answers

How to execute and get the output of a shell command in Node.js?

Sometimes, we want to execute and get the output of a shell command in Node.js.

In this article, we’ll look at how to execute and get the output of a shell command in Node.js.

How to execute and get the output of a shell command in Node.js?

To execute and get the output of a shell command in Node.js, we can use the child_process module’s exec method.

For instance, we write

const {
  exec
} = require('child_process');

exec(command, (error, stdout, stderr) => {
  console.log(error, stdout, stderr)
});

to call exec with the command string we want to run.

The 2nd argument is a callback that has the stdout and stderr output after running the command.

error has the error that’s thrown when the command is run.

Conclusion

To execute and get the output of a shell command in Node.js, we can use the child_process module’s exec method.

Categories
JavaScript Answers

How to use an http proxy with Node.js http.Client?

Sometimes, we want to use an http proxy with Node.js http.Client.

In this article, we’ll look at how to use an http proxy with Node.js http.Client.

How to use an http proxy with Node.js http.Client?

To use an http proxy with Node.js http.Client, we can use the http.get method to connect to the proxy.

For instance, we write

const http = require("http");

const options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};

http.get(options, (res) => {
  console.log(res);
  res.pipe(process.stdout);
});

to call http.get with the options for the connection.

We set the host to the proxy URL.

path has the path that we want to proxy with the proxy.

And headers has the Host with the host URL to proxy.

In the get callback, we get the response from res.

Conclusion

To use an http proxy with Node.js http.Client, we can use the http.get method to connect to the proxy.