Script Valley
Authentication From Scratch
Security HardeningLesson 5.3

Input validation and sanitization for auth routes

express-validator, email validation, password complexity rules, input sanitization, SQL injection via auth fields, error message consistency, reject unknown fields

Why Auth Inputs Need Validation

Unvalidated inputs lead to crashes, unexpected behavior, and injection attacks. Your auth routes accept user-controlled data and must validate it before any database or comparison logic runs.

npm install express-validator
const { body, validationResult } = require('express-validator');

const registerValidation = [
  body('email')
    .isEmail().normalizeEmail()
    .withMessage('Valid email required'),
  body('password')
    .isLength({ min: 8 })
    .matches(/[A-Z]/).withMessage('Password needs uppercase')
    .matches(/[0-9]/).withMessage('Password needs a number')
];

app.post('/auth/register', registerValidation, (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // Safe to proceed
});

Do Not Over-Restrict Passwords

Do not impose a maximum password length below 64 characters โ€” it signals you are storing passwords in a way that makes length matter (i.e., plaintext or weak encryption). bcrypt accepts up to 72 bytes natively. Reject passwords longer than 1000 characters to prevent DoS via intentionally slow bcrypt on huge inputs.

Up next

Setting security headers with Helmet.js

Sign in to track progress

Input validation and sanitization for auth routes โ€” Security Hardening โ€” Authentication From Scratch โ€” Script Valley โ€” Script Valley