EthicsComputerCourses
Join training +91 90532 10052

Secure Authentication Form Design

HTML · Lesson 171 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to build login, sign-up, password reset and OTP forms that are safe and easy to use. You will apply today's password rules, check for breached passwords and add passkey sign-in.

What you should know first: Secure Form Handling (HTTPS, POST, CSRF tokens, honeypots), Accessibility Engineering: WCAG 2.2 (Accessible Authentication) and Constraint Validation API. This lesson goes deeper on the forms that guard accounts. Password & Credential Autocomplete comes next and covers every autocomplete token.

Four forms, one set of rules

An account system has four doors, each with one special risk.

FormKey autocomplete valuesSpecial risk
Sign inusername, current-passwordPassword guessing, account enumeration
Sign upusername or email, new-passwordWeak or breached passwords
Password resetemail, then new-passwordToken theft, account takeover
OTP stepone-time-codeCode guessing, SMS interception

The basics for all four:

  • HTTPS and method="post", as in Secure Form Handling.
  • A CSRF token, even on the login form. Login CSRF signs the victim into the attacker's account, so anything they save, such as an address, goes to the attacker.
  • Never block paste or autofill. Password managers make long, unique passwords possible.

What modern password rules say

The US standards body NIST publishes Digital Identity Guidelines. Part B, SP 800-63B, covers authentication, and security teams worldwide treat it as the reference. We checked Revision 4 (SP 800-63B-4), finalised in 2025.

Rule in SP 800-63B-4Level
At least 15 characters when the password is the only factor; at least 8 when it is part of multi-factor loginSHALL
Allow at least 64 characters, all printable ASCII, spaces and UnicodeSHOULD
No composition rules ("one capital, one digit, one symbol")SHALL NOT
No forced periodic changes; force a change only on evidence of compromiseSHALL NOT / SHALL
Compare the whole password with a blocklist of breached, common and context words (like the site name or the username)SHALL
Allow password managers and autofill; allow pasteSHALL / SHOULD
Offer a way to show the password while typingSHOULD
No password hints and no security questionsSHALL NOT
Rate-limit failed attemptsSHALL
Verify the entire password, never a truncated partSHALL

Think of a bicycle lock: a 4-digit lock with fancy symbols is still only 4 digits, while a long chain is hard to cut. Length beats complexity: chai at platform 4 tastes best is far stronger than Pa$$w0rd!, and easier to remember.

Step 1: a sign-in form done right

Rohtak Books needs a sign-in page. Watch for these details:

  1. autocapitalize="none" and spellcheck="false" stop phones changing the email.
  2. The show-password button is type="button", so it never submits. Its text changes, and a status line confirms the change for screen reader users.
  3. A Caps Lock warning uses getModifierState("CapsLock").
  4. Before submitting, the field goes back to type="password".
HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign in to Rohtak Books</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 26rem; }
    label { display: block; margin-block-start: 12px; font-weight: bold; }
    input { inline-size: 100%; padding: 8px; box-sizing: border-box; font-size: 1rem; }
    .row { display: flex; gap: 8px; }
    .row input { flex: 1; }
    .note { color: #7a4100; margin: 4px 0; min-block-size: 1.2em; }
    button { min-block-size: 44px; padding-inline: 12px; }
  </style>
</head>
<body>
  <h1>Sign in to Rohtak Books</h1>
  <form id="login" action="https://www.example.com/login" method="post">
    <input type="hidden" name="csrf_token" value="value-from-the-server">

    <label for="email">Email</label>
    <input id="email" name="email" type="email" autocomplete="username"
           autocapitalize="none" spellcheck="false" required>

    <label for="password">Password</label>
    <div class="row">
      <input id="password" name="password" type="password" autocomplete="current-password"
             aria-describedby="caps" required>
      <button type="button" id="toggle" aria-controls="password">Show password</button>
    </div>
    <p id="caps" class="note" aria-live="polite"></p>
    <p id="shown" class="note" role="status"></p>

    <p><button>Sign in</button></p>
    <p><a href="#reset">Forgot your password?</a></p>
  </form>
  <p id="result"></p>

  <script>
    const form = document.querySelector("#login");
    const password = document.querySelector("#password");
    const toggle = document.querySelector("#toggle");

    toggle.addEventListener("click", () => {
      const willShow = password.type === "password";
      password.type = willShow ? "text" : "password";
      toggle.textContent = willShow ? "Hide password" : "Show password";
      document.querySelector("#shown").textContent =
        willShow ? "Your password is visible." : "Your password is hidden.";
    });

    password.addEventListener("keyup", (event) => {
      document.querySelector("#caps").textContent =
        event.getModifierState("CapsLock") ? "Caps Lock is on." : "";
    });

    form.addEventListener("submit", (event) => {
      event.preventDefault();          // demo only: a real form posts to the server
      password.type = "password";      // never leave the password showing
      toggle.textContent = "Show password";
      document.querySelector("#result").textContent =
        `Would POST ${form.email.value} and a ${password.value.length}-character password over HTTPS.`;
    });
  </script>
</body>
</html>

Type a password and press the button: the text appears and the status line confirms it. Turn on Caps Lock and type: the warning appears and is announced.

There are two correct toggle patterns: a fixed label with aria-pressed (as in the WCAG lesson), or a changing label (as here). Do not mix them: "Hide password, pressed" confuses everyone.

Step 2: a sign-up form with real password checks

The sign-up form follows the NIST table: one password field, a hint that states the rule, and messages that explain what to fix. WCAG 3.3.7 allows a "type it again" box for security, but a show-password toggle is easier.

We count characters with [...value].length, because minlength and maxlength count UTF-16 code units, where an emoji counts as two.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Create your account</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 28rem; }
    label { display: block; margin-block-start: 12px; font-weight: bold; }
    input { inline-size: 100%; padding: 8px; box-sizing: border-box; font-size: 1rem; }
    #rules { padding-inline-start: 0; list-style: none; }
    #rules li::before { content: "[ ] "; font-family: monospace; }
    #rules li.ok::before { content: "[x] "; }
    #rules li.ok { color: #166534; }
  </style>
</head>
<body>
  <h1>Create your Rohtak Books account</h1>
  <form id="signup" action="https://www.example.com/register" method="post">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" autocomplete="username" required>

    <label for="password">Choose a password</label>
    <input id="password" name="password" type="password" autocomplete="new-password"
           aria-describedby="rules" required>
    <ul id="rules">
      <li id="r-length">15 to 64 characters. A short sentence works well.</li>
      <li id="r-common">Not a common password, your email or the site name.</li>
    </ul>
    <p><button>Create account</button></p>
  </form>
  <p id="result" role="status"></p>

  <script>
    const form = document.querySelector("#signup");
    const email = document.querySelector("#email");
    const password = document.querySelector("#password");
    // A tiny sample. Real lists hold millions of breached passwords.
    const common = ["123456789012345", "password1234567", "qwertyuiopasdfg", "iloveyou1234567"];

    function problem() {
      const value = password.value;
      const count = [...value].length;               // characters, not code units
      const lower = value.trim().toLowerCase();
      const mail = email.value.trim().toLowerCase();
      const blocked = [...common, "rohtakbooks", mail, mail.split("@")[0]];
      document.querySelector("#r-length").classList.toggle("ok", count >= 15 && count <= 64);
      const isBlocked = value !== "" && blocked.includes(lower);
      document.querySelector("#r-common").classList.toggle("ok", value !== "" && !isBlocked);
      if (count < 15 || count > 64) return `Use 15 to 64 characters (you have ${count}).`;
      if (isBlocked) return "That password is too easy to guess. Choose another.";
      return "";
    }

    password.addEventListener("input", () => password.setCustomValidity(problem()));
    email.addEventListener("input", () => password.setCustomValidity(problem()));

    form.addEventListener("submit", (event) => {
      event.preventDefault();                         // demo only
      password.setCustomValidity(problem());
      if (form.reportValidity()) {
        document.querySelector("#result").textContent =
          "Looks good. The server now checks the breach list and stores a hash.";
      }
    });
  </script>
</body>
</html>

Try Rohtak@2026: too short. Try 123456789012345 or your email: blocked. chai at platform 4 tastes best is accepted, and so is my rohtak tea stall opens at six, because NIST says compare the whole password, not words inside it.

Step 3: the PHP side

The server repeats the checks and adds a breach check. The Have I Been Pwned "Pwned Passwords" service uses k-anonymity: you send only the first five characters of the password's SHA-1 hash, it returns every breached hash starting with them, and you look for yours locally.

PHP
<?php
declare(strict_types=1);

const SITE_NAME = 'rohtakbooks';

function hashPassword(string $password): string
{
    // Argon2id has no 72-byte limit; check password_algos() on your server
    return password_hash($password, PASSWORD_ARGON2ID);
}

function isBreached(string $password): bool
{
    $sha1 = strtoupper(sha1($password));
    $prefix = substr($sha1, 0, 5);           // only 5 characters leave your server
    $suffix = substr($sha1, 5);
    $context = stream_context_create(['http' => ['timeout' => 3, 'header' => "Add-Padding: true\r\n"]]);
    $body = @file_get_contents('https://api.pwnedpasswords.com/range/' . $prefix, false, $context);
    if ($body === false) {
        return false;                         // service down: fall back to your local list
    }
    foreach (explode("\n", $body) as $line) {
        [$hashSuffix, $count] = array_pad(explode(':', trim($line)), 2, '0');
        if ($hashSuffix === $suffix && (int) $count > 0) {
            return true;
        }
    }
    return false;
}

function passwordProblem(string $password, string $email): ?string
{
    $length = mb_strlen($password, 'UTF-8');  // characters, not bytes
    if ($length < 15 || $length > 64) {
        return 'Use 15 to 64 characters. A short sentence is easy to remember.';
    }
    $lower = mb_strtolower(trim($password), 'UTF-8');
    $email = mb_strtolower($email, 'UTF-8');
    $blocked = [SITE_NAME, $email, strstr($email, '@', true), 'password1234567', '123456789012345'];
    if (in_array($lower, $blocked, true)) {   // compare the whole password
        return 'That password is too easy to guess. Choose another.';
    }
    if (isBreached($password)) {
        return 'That password has appeared in a data breach. Choose another.';
    }
    return null;
}

We ran passwordProblem() with PHP 8.4 for five passwords and the email meera@example.com, with the real breach service:

Output
'short pass'                       => Use 15 to 64 characters. A short sentence is easy to remember.
'123456789012345'                  => That password is too easy to guess. Choose another.
'password1234567890'               => That password has appeared in a data breach. Choose another.
'meera@example.com'                => That password is too easy to guess. Choose another.
'chai at platform 4 tastes best'   => OK

Why Argon2id and not the default? PASSWORD_DEFAULT is still bcrypt, which silently uses only the first 72 bytes. In our test, a bcrypt hash of 80 letters also accepted a different password that matched only the first 72. A Hindi passphrase uses 3 bytes per character, so it hits that limit after 24 characters. If your PHP lacks Argon2id, keep bcrypt and reject passwords over 72 bytes with strlen().

Sign-in uses password_verify(). Two details stop attackers learning which emails exist:

PHP
// Made once with password_hash(); used when the email is unknown
const DUMMY_HASH = '$argon2id$v=19$m=65536,t=4,p=1$NzE0TzFtU1VzSDl3TXFmZw$Vh3wLCOBXyTk1Lkp1bqTgWHf95kaFcju63SBUuaVBT4';

function attemptLogin(PDO $pdo, string $email, string $password): ?int
{
    $stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
    $stmt->execute([mb_strtolower(trim($email), 'UTF-8')]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // Always run one password_verify(), so unknown emails take as long as known ones
    $hash = $user['password_hash'] ?? DUMMY_HASH;
    if (!password_verify($password, $hash) || $user === false) {
        return null;
    }
    if (password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
        $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
            ->execute([password_hash($password, PASSWORD_ARGON2ID), $user['id']]);
    }
    return (int) $user['id'];
}

The caller shows one message for every failure, "Email or password is incorrect", and records it for the rate limiter. On success it calls session_regenerate_id(true), so a session ID planted before login becomes useless. Our test used an SQLite user with an old bcrypt hash:

Output
Stored hash starts: $2y$12$4q
NULL
NULL
int(1)
Stored hash starts: $argon2id

Wrong password and unknown email both return NULL. The correct login succeeds and quietly upgrades the old hash.

Rate limiting and lockout

Think of a bank locker. Three wrong keys should not seal it forever, or a prankster could lock everyone out, but nobody should get a thousand tries either. In general terms:

  • Count failures per account and per IP address. Attackers either try many passwords on one account, or one common password on many accounts (password spraying).
  • Slow down before you stop. Add growing delays, for example 30 seconds, then minutes. NIST caps consecutive failures at 100 before an account is disabled, and allows lower limits.
  • Avoid permanent lockout. Unlock automatically after a delay, or offer a reset email, and notify the user.
  • Limit every door, including reset and OTP forms, and answer 429 Too Many Requests with a clear message.

Password reset without account takeover

Kabir from Pune forgot his password. The flow:

  1. He enters his email (autocomplete="email"). The page always says "If an account exists for this email, we have sent a link", whether or not it exists.
  2. The server makes a token with bin2hex(random_bytes(32)), stores only its SHA-256 hash with a short expiry (about 30 minutes), and emails the link.
  3. The reset page checks the hash and expiry, marks the token used, and shows a new-password field plus a hidden username field for password managers.
  4. Afterwards, delete his reset tokens, end other sessions and email him about the change.
HTML
<form action="/reset-password" method="post">
  <input type="hidden" name="token" value="TOKEN_FROM_THE_LINK">
  <input type="email" name="username" autocomplete="username" value="kabir@example.com" hidden>
  <label for="new">New password</label>
  <input id="new" name="password" type="password" autocomplete="new-password" required>
  <button>Save new password</button>
</form>

The token sits in the URL, so keep third-party scripts and images off this page, and send a strict Referrer Policy so the URL cannot leak.

OTP fields and WebOTP

A one-time password (OTP) is a short code sent by SMS or shown in an authenticator app. Use one text field:

HTML
<label for="otp">6-digit code sent to +91 98xxx xx421</label>
<input id="otp" name="otp" type="text" inputmode="numeric" autocomplete="one-time-code"
       pattern="[0-9]{6}" maxlength="6" required>

inputmode="numeric" shows a number pad; type="number" would drop leading zeros. one-time-code lets phones offer the code from a fresh SMS. Six separate boxes often break that autofill and paste, which WCAG 3.3.8 needs.

The WebOTP API goes further: the page asks the browser to read the code from an SMS whose last line is @www.example.com #123456.

JavaScript
if ("OTPCredential" in window) {
  const controller = new AbortController();
  form.addEventListener("submit", () => controller.abort());
  navigator.credentials.get({ otp: { transport: ["sms"] }, signal: controller.signal })
    .then((otp) => { input.value = otp.code; form.requestSubmit(); })
    .catch(() => {});   // user declined or timed out: they can still type it
}

On Chrome for Android the user taps "Allow" on a prompt and the form fills itself. It needs HTTPS and a real SMS, so it cannot run in the editor. MDN marks WebOTP experimental: it works in Chromium browsers, not Firefox, and Safari fills one-time-code fields from Messages instead. SMS codes can be phished, so expire them in minutes and limit attempts.

Passkeys: sign-in without a password

A passkey is a key pair made by the user's device through the WebAuthn standard. The private key never leaves the device; the server stores only the public key. Each passkey works only on the site that created it, so a fake look-alike page cannot use it. That makes passkeys phishing-resistant.

Add webauthn as the last token of the username field. Browsers then show saved passkeys in the same autofill list as passwords (called conditional mediation):

HTML
<input id="email" name="email" type="email" autocomplete="username webauthn">
JavaScript
if (window.PublicKeyCredential && await PublicKeyCredential.isConditionalMediationAvailable?.()) {
  const options = await (await fetch("/passkey/options")).json();   // challenge from the server
  const credential = await navigator.credentials.get({
    mediation: "conditional",
    publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
  });
  await fetch("/passkey/verify", { method: "POST", body: JSON.stringify(credential.toJSON()) });
}

isConditionalMediationAvailable() works in Chrome and Edge 108+, Firefox 119+ and Safari 16+; parseRequestOptionsFromJSON() and toJSON() need Chrome 129+, Firefox 119+ or Safari 18.4+. Verify the response on the server with a maintained WebAuthn library, and keep the password form as a fallback.

Common mistakes

  • Blocking paste or autofill. It fails WCAG 3.3.8 and pushes users to weak passwords.
  • Complexity rules and forced expiry. Use length and a blocklist instead.
  • "No account with this email." Every failure path must give the same message.
  • bcrypt with long Unicode passwords. It silently ignores everything after 72 bytes.
  • Reset tokens stored in plain text or that never expire.
  • type="number" for OTPs. Leading zeros vanish.

Interview questions

1. What does NIST SP 800-63B-4 say about password rules?

At least 15 characters when the password is the only factor, and at least 64 allowed. No composition rules and no forced periodic changes. The whole password must be checked against a blocklist of breached, common and context-specific values, and paste and password managers must work.

2. How do you avoid account enumeration on login and reset forms?

Return the same message, status code and similar timing whether or not the account exists. On login, verify against a dummy hash for unknown users; on reset, always say "if an account exists, we sent a link".

3. Why is PASSWORD_ARGON2ID safer than bcrypt for long passwords in PHP?

bcrypt uses only the first 72 bytes and silently ignores the rest. Argon2id has no such limit and is memory-hard, which slows GPU cracking.

4. Which attributes should an OTP field have?

type="text", inputmode="numeric", autocomplete="one-time-code", a pattern such as [0-9]{6} and a label. One field keeps paste and SMS autofill working.

5. What makes passkeys phishing-resistant?

The browser binds each credential to the site's domain, so a look-alike domain cannot use it. The server stores only a public key, which is useless to thieves.

Key points

  • Every authentication form needs HTTPS, POST, a CSRF token and correct autocomplete values.
  • Follow NIST SP 800-63B-4: length over complexity, a whole-password blocklist, no expiry, no hints, paste allowed.
  • Offer an accessible show-password toggle and a Caps Lock warning.
  • Hash with password_hash() (Argon2id where available), check with password_verify(), upgrade with password_needs_rehash().
  • Use identical messages for every failure, and rate-limit without permanent lockout.
  • OTP fields use one-time-code and inputmode="numeric"; passkeys use autocomplete="username webauthn".

Exercise

Build a "Change password" page for a Kochi student portal: current password, new password with a show-password toggle, a hidden username field and a CSRF token. In script, reject new passwords under 15 characters or equal to the current one. Then write a PHP function changePassword(PDO $pdo, int $userId, string $current, string $new): string that verifies the current password, checks the new one with passwordProblem() and stores an Argon2id hash.

Show solution
HTML
<form id="change" action="/change-password" method="post">
  <input type="hidden" name="csrf_token" value="value-from-the-server">
  <input type="email" name="username" autocomplete="username" value="meera@example.com" hidden>
  <label for="current">Current password</label>
  <input id="current" name="current" type="password" autocomplete="current-password" required>
  <label for="new">New password (15 or more characters)</label>
  <input id="new" name="new" type="password" autocomplete="new-password" required>
  <button type="button" id="toggle" aria-pressed="false" aria-controls="new">Show password</button>
  <button>Change password</button>
</form>
<script>
  const current = document.querySelector("#current");
  const next = document.querySelector("#new");
  const toggle = document.querySelector("#toggle");
  toggle.addEventListener("click", () => {
    const show = next.type === "password";
    next.type = show ? "text" : "password";
    toggle.setAttribute("aria-pressed", String(show));
  });
  document.querySelector("#change").addEventListener("submit", (event) => {
    const count = [...next.value].length;
    next.setCustomValidity(count < 15 ? "Use at least 15 characters."
      : next.value === current.value ? "Choose a password you have not used here." : "");
    if (!next.reportValidity()) event.preventDefault();
    next.type = "password";
  });
</script>
PHP
function changePassword(PDO $pdo, int $userId, string $current, string $new): string
{
    $stmt = $pdo->prepare('SELECT email, password_hash FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user === false || !password_verify($current, $user['password_hash'])) {
        return 'Your current password is not correct.';
    }
    $problem = passwordProblem($new, $user['email']);
    if ($problem !== null) {
        return $problem;
    }
    $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
        ->execute([password_hash($new, PASSWORD_ARGON2ID), $userId]);
    return 'Your password has been changed.';
}

This page uses the fixed-label aria-pressed toggle. A real handler also checks the CSRF token, rate-limits attempts and emails the user about the change.

Quick Quiz

1. Under NIST SP 800-63B-4, what is the minimum length for a password that is the only login factor?

2. Why does the login code call password_verify() with a dummy hash when the email is unknown?

3. Which input is best for a 6-digit SMS code?

4. Which autocomplete value lets the browser offer passkeys in the username autofill list?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call