Agenda

<aside> 📌 Reminders

Storing and Verifying Passwords as Salted Hashes

What is a Salted Hash?

A hash is a one-way cryptographic function that converts data (like passwords) into a fixed-length string. A salt adds random data to the password before hashing it, increasing its security by preventing attacks like dictionary and rainbow table attacks.

Storing passwords in plaintext is insecure. Storing passwords as salted hashes ensures that even if the database is compromised, attackers can't easily reverse-engineer the passwords.

Using the bcrypt package, you can hash passwords and store them in a secure way. When users sign in, the stored hash is compared with the hash of the provided password.

import { compare, genSalt, hash } from "bcrypt";

// Generating a salted hash

genSalt(10, function (err, salt) {

hash(password, salt, function (err, hash) {

// Store hash in the database

});

});

// Verifying password during sign in

compare(password, storedHash, function(err, result) {

if (result) {

// Password matches

}

});

Stateful Authentication Using Session Cookies

import session from "express-session";

app.use(

session({

secret: "please change this secret",

resave: false,

saveUninitialized: true,

})

);

// Store username in session

req.session.username = "user123";

Authorization

function isAuthenticated(req, res, next) {

if (!req.session.username) return res.status(401).end("access denied");

next();

}

// Example of protecting a route

app.post('/api/messages/', isAuthenticated, function (req, res) {

// Only authenticated users can post messages

});