
Learn How to Master Digital Trust

The State of Consumer Digital ID 2024

Top CIAM Platform 2024
In this blog, we’ll be implementing authentication with password hashing in a Node.js web application. For this, we’ll be using crypto, a package password hashing for Node.js.
The Crypto module for Node JS helps developers to hash user passwords.
Pre-requisites:
- Basic knowledge of HTML/JavaScript
- Node js should be installed in your system.
- express module for creating the server.
- mongoose module for MongoDB connection and queries.
- Crypto module for hashing.
- body-parser for parsing JSON data
Step 1. First, create a directory structure as below :
hashApp
1--model
2----user.js
3--route
4----user.js
5--server.jsStep 2. Create model/user.js file and add the following code :
1// Importing modules
2const mongoose = require('mongoose');
3var crypto = require('crypto');
4// Creating user schema
5const UserSchema = mongoose.Schema({
6name : {
7type : String,
8required : true
9},
10email : {
11type : String,
12required : true
13},
14hash : String,
15salt : String
16});
17// Method to set salt and hash the password for a user
18UserSchema.methods.setPassword = function(password) {
19// Creating a unique salt for a particular user
20this.salt = crypto.randomBytes(16).toString('hex');
21// Hashing user's salt and password with 1000 iterations,
22
23this.hash = crypto.pbkdf2Sync(password, this.salt,
241000, 64, `sha512`).toString(`hex`);
25
26};
27// Method to check the entered password is correct or not
28UserSchema.methods.validPassword = function(password) {
29var hash = crypto.pbkdf2Sync(password,
30this.salt, 1000, 64, sha512).toString(hex);
31return this.hash === hash;
32};
33// Exporting module to allow it to be imported in other files
34const User = module.exports = mongoose.model('User', UserSchema);Step 3. Create route/user.js file and add the following code:
1// Importing modules
2const express = require('express');
3const router = express.Router();
4// Importing User Schema
5const User = require('../model/user');
6// User login api
7router.post('/login', (req, res) => {
8// Find user with requested email
9User.findOne({ email : req.body.email }, function(err, user) {
10 if (user === null) {
11 return res.status(400).send({
12 message : "User not found."
13 });
14 }
15 else {
16 if (user.validPassword(req.body.password)) {
17 return res.status(201).send({
18 message : "User Logged In",
19 })
20 }
21 else {
22 return res.status(400).send({
23 message : "Wrong Password"
24 });
25 }
26 }
27});
28
29});
30// User signup api
31router.post('/signup', (req, res, next) => {
32// Creating empty user object
33let newUser = new User();
34// Initialize newUser object with request data
35newUser.name = req.body.name,
36
37newUser.email = req.body.email,
38
39
40newUser.password=req.body.password
41
42 // Call setPassword function to hash password
43 newUser.setPassword(req.body.password);
44
45// Save newUser object to database
46newUser.save((err, User) => {
47 if (err) {
48 return res.status(400).send({
49 message : "Failed to add user."
50 });
51 }
52 else {
53 return res.status(201).send({
54 message : "User added successfully."
55 });
56 }
57});
58
59});
60// Export module to allow it to be imported in other files
61module.exports = router;Step 4. Create server.js file :
1// Importing modules
2var express = require('express');
3var mongoose = require('mongoose');
4var bodyparser = require('body-parser');
5// Initialize express app
6var app = express();
7// Mongodb connection url
8var MONGODB_URI = "mongodb://localhost:27017/hashAppDb";
9// Connect to MongoDB
10mongoose.connect(MONGODB_URI);
11mongoose.connection.on('connected', () => {
12console.log('Connected to MongoDB @ 27017');
13});
14// Using bodyparser to parse json data
15app.use(bodyparser.json());
16// Importing routes
17const user = require('./route/user');
18// Use user route when url matches /api/user/
19app.use('/api/user', user);
20// Creating server
21const port = 3000;
22app.listen(port, () => {
23console.log("Server ru
24nning at port: " + port);
25});Step 5. Run server.js file using command
1node server.jsStep 6. Open Postman and create a post request to localhost:3000/api/user/signup with following body parameter:
1{
2"name" : "test".
3"email" : "test@test.com",
4"password" : "test1234"
5}Run the request and you will get a success response:
1{
2"message" : "user added sucessfully"
3}User data is stored in the database as below:
1"_id": {
2 "$oid": "5ab71ef2afb6db0148052f6f"
3 },
4 "name": "test",
5 "email": "test@test.com",
6 "salt": "ddee18ef6a6804fbb919b25f790005e3",
7 "hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110
8 b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",
9 "__v": 0
10}If we have sensitive data or information that you need to be protected, ensuring it is secured correctly is important. With the above process, we can now successfully store our hashed password into our database with a bit of additional security.
You can check the code on Github.

