nodejs logo

Secure Authentication in Node.js

Overview

Secure authentication is crucial for protecting user data and ensuring that only authorized users can access certain resources. This guide covers best practices and tools to implement secure authentication in Node.js applications.

Using bcrypt for Password Hashing

Passwords should never be stored in plain text. Use the bcrypt library to hash passwords:

const bcrypt = require('bcrypt');

// Hash a password
const saltRounds = 10;
const plainPassword = 'mySecretPassword';

bcrypt.hash(plainPassword, saltRounds, (err, hash) => {
  if (err) throw err;
  console.log('Hashed Password:', hash);
});

Verifying Passwords

When a user logs in, verify their password against the hashed password:

// Verify a password
bcrypt.compare(plainPassword, hashFromDatabase, (err, result) => {
  if (err) throw err;
  if (result) {
    console.log('Password is valid!');
  } else {
    console.log('Invalid password.');
  }
});

Using JSON Web Tokens (JWT)

JSON Web Tokens provide a way to securely transmit information between parties as a JSON object. Install the jsonwebtoken package:

npm install jsonwebtoken

Generate a token after successful authentication:

const jwt = require('jsonwebtoken');

// Generate a token
const user = { id: userId }; // User information
const token = jwt.sign(user, 'your_jwt_secret', { expiresIn: '1h' });
console.log('Generated Token:', token);

Middleware for Protected Routes

Use middleware to protect routes by verifying the token:

// Middleware to check token
const authenticateToken = (req, res, next) => {
  const token = req.headers['authorization'];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, 'your_jwt_secret', (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

Best Practices

Follow these best practices to enhance security:

  • Always hash passwords using a strong hashing algorithm like bcrypt.
  • Use HTTPS to encrypt data in transit.
  • Implement rate limiting to prevent brute-force attacks.
  • Store JWTs securely and use short expiration times.
© 2024 Secure Authentication Guide