Build Node.js User Authentication – Password Login

We will be covering all of the security concerns that you will run into while building an authentication system. We will also cover how to securely store a password in case of a database breach.

Concepts

  • What a password salt is
  • How to properly hash a password
  • How to store passwords
  • Basic express server setup
  • User login

Basic express server setup

Step 1. npm init –force

Step 2. npm i express bcrypt

Step 3. npm i –save-dev nodemon

Step 4. Add the run comman into package.json
“scripts”: {
“devStart”: “nodemon server.js”
}

Step 5. Add file server.js

Step 6. Import modules into server.js

Step 7. Install ‘REST Client’ plugins into VisualStudioCode for test the REST API

Step 8. Add request.rest file and add the GET, POST, Login request

Step 9. Create GET, POST route in server.js

Step 10. Add middle ware app.use(express.json()) to response in JSON format

Step 11. Add the ‘bcrypt’ module

Step 12. Add the Registration process with Hashing functionality

const salt = await bcrypt.genSalt()
	const hashedPassword = await bcrypt.hash(req.body.password, salt)

Or Single line hashed password

const hashedPassword = await bcrypt.hash(req.body.password, 10)

Step 13. Add the Login process with hash compare functionality


	const user = users.find(user => user.name === req.body.name)
	if(await bcrypt.compare(req.body.password, user.password)) {
      		res.send('Success')
    	} else {
      		res.send('Not Allowed')
    	}

we want to make sure that our passwords are hashed so that even if someone gets access to our database they won’t actually know what the users passwords are, this is where bcrypt comes in.

To hash a password we need to have two steps we need to number one create a salt and then we need to use that salt along with the password to create a hashed password
We actually want to use bcrypt which is an asynchronous library so let’s make sure we use an asynchronous function in here.


const express = require('express')
const app = express()
const bcrypt = require('bcrypt')

app.use(express.json())

const users = []

app.get('/users', (req, res) => {
  res.json(users)
})

app.post('/users', async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    const user = { name: req.body.name, password: hashedPassword }
    users.push(user)
    res.status(201).send()
  } catch {
    res.status(500).send()
  }
})

app.post('/users/login', async (req, res) => {
  const user = users.find(user => user.name === req.body.name)
  if (user == null) {
    return res.status(400).send('Cannot find user')
  }
  try {
    if(await bcrypt.compare(req.body.password, user.password)) {
      res.send('Success')
    } else {
      res.send('Not Allowed')
    }
  } catch {
    res.status(500).send()
  }
})

app.listen(3000)

Reference

Leave a Reply

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