Inpute validation and authentication flow | Cyber Security Tutorial - Learn with VOKS
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL
Back Next

Inpute validation and authentication flow

Learn this topic step-by-step with VOKS Tutorials.

Input Validation And Authentication Flow

In modern applications (web, mobile, or desktop), Input Validation and Authentication Flow are two fundamental security concepts. If you understand these properly, you understand the foundation of secure software.

What Is Input Validation?

Definition

Input Validation is the process of checking whether the data a user provides is correct, safe, and in the expected format before your system uses it.

Whenever a user enters:

  • Username
  • Email
  • Password
  • Phone number
  • Search text
  • File uploads

That is input.

If you do not validate input, attackers can:

  • Break your system
  • Steal data
  • Inject malicious code
  • Crash your application

Why Input Validation Is Important

Imagine someone enters this into a login field:

' OR 1=1 --

If your system blindly trusts that input, it might:

  • Bypass authentication
  • Expose your database
  • Execute unintended commands

Validation protects your system from:

  • SQL Injection
  • Cross-Site Scripting (XSS)
  • Command injection
  • Invalid data
  • Application crashes

Types Of Input Validation

1. Client-Side Validation

This happens in the browser (using JavaScript).

Purpose:

  • Improve user experience
  • Prevent obvious mistakes

Example:

  • Checking if email contains "@"
  • Password is at least 8 characters

Important: Client-side validation is NOT secure by itself. Attackers can bypass it.

2. Server-Side Validation

This happens on the backend (server).

Purpose:

  • Enforce security
  • Prevent malicious input
  • Protect database

Server-side validation is mandatory.

Basic Input Validation Example (Node.js + Express)

Here is a simple example of validating a login request.

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

app.use(express.json());

app.post('/login', (req, res) => {
    const { email, password } = req.body;

    // Check if fields exist
    if (!email || !password) {
        return res.status(400).json({ message: "Email and password are required." });
    }

    // Check email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        return res.status(400).json({ message: "Invalid email format." });
    }

    // Check password length
    if (password.length < 8) {
        return res.status(400).json({ message: "Password must be at least 8 characters." });
    }

    res.json({ message: "Input validated successfully." });
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

This example checks:

  • Missing fields
  • Invalid email format
  • Weak password

But validation alone does not log users in. That is where Authentication Flow comes in.

What Is Authentication?

Definition

Authentication is the process of verifying who a user is.

It answers this question:

"Are you really who you claim to be?"

Common authentication methods:

  • Username and password
  • One-Time Password (OTP)
  • Biometric authentication
  • OAuth (Google login, etc.)

Authentication Flow Explained Step-By-Step

Let us walk through a typical login process.

Step 1: User Sends Login Request

User enters:

  • Email
  • Password

The browser sends data to the server.

Step 2: Input Validation

The server checks:

  • Are fields present?
  • Is email valid format?
  • Is password long enough?

If validation fails → reject request.

Step 3: Find User In Database

Server searches database for the email.

If user does not exist → return error.

Step 4: Compare Passwords Securely

Important: Passwords should NEVER be stored in plain text.

Instead:

  • Hash the password
  • Store the hash

When user logs in:

  • Hash the entered password
  • Compare with stored hash

If hashes match → authentication successful.

Step 5: Generate Authentication Token

If login is successful:

  • Server generates a token (usually JWT)
  • Sends token back to client
  • Client stores token
  • Token is sent with future requests

Full Authentication Flow Example (Node.js + Express + JWT)

Below is a simplified example.

You will need:

  • express
  • bcrypt
  • jsonwebtoken

Install:

npm install express bcrypt jsonwebtoken

Now the code:

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET_KEY = "mysecretkey";

// Fake database
let users = [];

// Register route
app.post('/register', async (req, res) => {
    const { email, password } = req.body;

    // Input validation
    if (!email || !password) {
        return res.status(400).json({ message: "Email and password required." });
    }

    if (password.length < 8) {
        return res.status(400).json({ message: "Password must be at least 8 characters." });
    }

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 10);

    // Save user
    users.push({ email, password: hashedPassword });

    res.json({ message: "User registered successfully." });
});

// Login route
app.post('/login', async (req, res) => {
    const { email, password } = req.body;

    // Validate input
    if (!email || !password) {
        return res.status(400).json({ message: "Email and password required." });
    }

    // Find user
    const user = users.find(u => u.email === email);

    if (!user) {
        return res.status(400).json({ message: "Invalid credentials." });
    }

    // Compare password
    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {
        return res.status(400).json({ message: "Invalid credentials." });
    }

    // Generate token
    const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1h" });

    res.json({ message: "Login successful.", token });
});

// Protected route example
app.get('/dashboard', (req, res) => {
    const authHeader = req.headers['authorization'];

    if (!authHeader) {
        return res.status(401).json({ message: "Access denied. No token provided." });
    }

    const token = authHeader.split(" ")[1];

    try {
        const verified = jwt.verify(token, SECRET_KEY);
        res.json({ message: "Welcome to dashboard.", user: verified });
    } catch (err) {
        res.status(400).json({ message: "Invalid token." });
    }
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

How Input Validation And Authentication Work Together

Here is the relationship:

  1. Input validation ensures the data is safe and correct.
  2. Authentication verifies the identity.
  3. Token management maintains logged-in state.

Without validation:

  • Attackers can bypass authentication.

Without authentication:

  • Anyone can access protected resources.

They are separate but tightly connected security layers.

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const SECRET_KEY = "mysecretkey";

// Fake database
let users = [];

// Register route
app.post('/register', async (req, res) => {
    const { email, password } = req.body;

    if (!email || !password) {
        return res.status(400).json({ message: "Email and password required." });
    }

    if (password.length < 8) {
        return res.status(400).json({ message: "Password must be at least 8 characters." });
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    users.push({ email, password: hashedPassword });

    res.json({ message: "User registered successfully." });
});

// Login route
app.post('/login', async (req, res) => {
    const { email, password } = req.body;

    if (!email || !password) {
        return res.status(400).json({ message: "Email and password required." });
    }

    const user = users.find(u => u.email === email);

    if (!user) {
        return res.status(400).json({ message: "Invalid credentials." });
    }

    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {
        return res.status(400).json({ message: "Invalid credentials." });
    }

    const token = jwt.sign({ email: user.email }, SECRET_KEY, { expiresIn: "1h" });

    res.json({ message: "Login successful.", token });
});

// Protected route
app.get('/dashboard', (req, res) => {
    const authHeader = req.headers['authorization'];

    if (!authHeader) {
        return res.status(401).json({ message: "Access denied. No token provided." });
    }

    const token = authHeader.split(" ")[1];

    try {
        const verified = jwt.verify(token, SECRET_KEY);
        res.json({ message: "Welcome to dashboard.", user: verified });
    } catch (err) {
        res.status(400).json({ message: "Invalid token." });
    }
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});
QUICK KNOWLEDGE CHECK

Test Your Understanding

Answer 5 questions generated from this lesson. Your result is calculated instantly and is not saved.

0 / 5 answered
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL
Course contents
Cyber Security
01 Introduction 02 Types of Cyber Threats 03 Cyber Security Domains 04 CIA Triad (Confidentiality Integrity Availability) 05 Career paths in Cyber Security 06 Certifications 07 Ethics and Responsible Disclosure 08 Laws and Regulation (e.g. GDPR, NDPR) 09 What is an OS? 10 Types: Window, Linus, macOS 11 Command-line vs GUI 12 OS Internals Overview (filesystems, processes, permissions) 13 Windows command prompt basics 14 Linux Bash Basics 15 File System Navigation 16 Basic Scripting 17 IP Addressing 18 DNS, DHCP 19 Mac Address 20 OSI VS TCP/IP Models 21 Ports and Protocols (TCP, UDP) 22 Common Protocols (HTTPS, FTP, SSH, etc.) 23 Packet structure 24 Firewalls, IDS/IPS, VPNs 25 Common attacks: MITM, Sniffing 26 Secure Network Practices 27 How the Web works 28 HTTP vs HTTPS 29 URLs, Headers, Cookies 30 Client-Server Architecture 31 Introduction To Web Security 32 OWASP Top 10 Overview 33 Common Threats (XSS, SQLi, CSRF) 34 Inpute validation and authentication flow 35 Basic Exploitation demo (e.g. XSS) 36 Burp Suite Introduction 37 Using a Browser For Testing 38 Password security 39 MFA-Antivirus 40 Cyber Hygeine Practice 41 Intro To Tools: Nmap, Wireshark, Netstat