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.
