Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Authentication and Errors

Password Hashing and Registration

Store passwords safely in an Axum API with Argon2id: salts, PHC strings, spawn_blocking, login verification, constant-time compare and user-enumeration pitfalls, plus runnable teaching stand-ins.

Authentication starts with accounts, and accounts start with passwords. The first rule is absolute: never store a password, not even encrypted. Store a hash made with a deliberately slow, salted, password-hashing function. If your database leaks, attackers then face the cost of guessing every password one by one instead of reading them off.

This lesson covers registration and login in Axum: what to hash with, how to store the result, how to verify it, and the traps (blocking the runtime, leaking which emails exist, timing leaks). The argon2 crate is not available on this site's runner, so the real code is read-only. The runnable examples use a toy hash that exists only to demonstrate the structure (salt, stored format, verify); it is not secure and must never be used for real passwords.

What to use

Use a memory-hard password hash: Argon2id (the current recommendation), or scrypt or bcrypt if you must. Do not use SHA-256, MD5 or any fast hash: attackers can try billions of guesses per second on a GPU. Argon2 is configurable in time, memory and parallelism so each guess costs real resources.

Each password gets its own random salt, so two users with the same password get different hashes and precomputed tables (rainbow tables) are useless. The argon2 crate packs algorithm, parameters, salt and hash into one self-describing PHC string:

TEXT
$argon2id$v=19$m=19456,t=2,p=1$c29tZXNhbHRieXRlcw$Zk5r1xv3Pq...

Store that single string in a password_hash TEXT column. When parameters change over time, old hashes still verify because each carries its own parameters.

Real code: hash and verify

Rust
// Real code: read-only. Cargo: argon2 = "0.5"
use argon2::{
    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Argon2,
};

fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
    let salt = SaltString::generate(&mut OsRng);
    Ok(Argon2::default().hash_password(password.as_bytes(), &salt)?.to_string())
}

fn verify_password(password: &str, stored: &str) -> bool {
    match PasswordHash::new(stored) {
        Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
        Err(_) => false,
    }
}

verify_password compares in constant time inside the library, so an attacker cannot learn how many leading bytes were right from the response time.

Registration handler

Hashing is CPU and memory heavy (tens of milliseconds by design). Running it directly in an async handler would block a runtime worker, so push it to the blocking pool, as the Tokio lesson explained.

Rust
#[derive(Deserialize)]
struct Register {
    email: String,
    password: String,
}

async fn register(
    State(db): State<PgPool>,
    Json(input): Json<Register>,
) -> Result<StatusCode, AppError> {
    let email = input.email.trim().to_lowercase();
    if !email.contains('@') || input.password.len() < 8 {
        return Err(AppError::BadRequest("invalid email or password too short".into()));
    }

    let password = input.password;
    let hash = tokio::task::spawn_blocking(move || hash_password(&password))
        .await
        .map_err(|e| AppError::Internal(e.into()))?
        .map_err(|e| AppError::Internal(anyhow::anyhow!("{e}")))?;

    sqlx::query("INSERT INTO users (email, password_hash) VALUES ($1, $2)")
        .bind(&email)
        .bind(&hash)
        .execute(&db)
        .await?; // unique violation on email -> 409 via From<sqlx::Error>

    Ok(StatusCode::CREATED)
}

Normalise emails (trim, lowercase) before storing and put a unique index on the column; the database, not a pre-check query, is the authority that prevents duplicates under concurrency.

Login handler and enumeration

Rust
async fn login(State(db): State<PgPool>, Json(input): Json<Login>) -> Result<Json<TokenResponse>, AppError> {
    let email = input.email.trim().to_lowercase();
    let user: Option<(i64, String)> =
        sqlx::query_as("SELECT id, password_hash FROM users WHERE email = $1")
            .bind(&email)
            .fetch_optional(&db)
            .await?;

    // Verify against a dummy hash when the user is missing, so the timing is similar.
    let stored = user.as_ref().map(|u| u.1.clone()).unwrap_or_else(|| DUMMY_HASH.to_string());
    let password = input.password;
    let ok = tokio::task::spawn_blocking(move || verify_password(&password, &stored))
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

    match (user, ok) {
        (Some((id, _)), true) => Ok(Json(TokenResponse { token: issue_token(id)? })),
        _ => Err(AppError::Unauthorized), // same answer for unknown email and wrong password
    }
}

Two defences: answer with the same message whether the email or the password was wrong (otherwise attackers can test which emails are registered), and do equal work in both cases so response time does not leak it either.

Stand-in: salts, PHC-style storage, verification

This toy shows the shape of the scheme with a trivial hash function. The real security comes from Argon2's cost, which this stand-in does not have.

Rust Salted hash, stored string, verify (TOY stand-in, not secure)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Different salts produce different stored strings even for identical passwords, and verification re-derives the hash using the parameters inside the string.

Password policy

Require a sensible minimum length (8 or more; longer is better), allow long passphrases and all characters, and do not force silly composition rules. Check against a list of known breached passwords if you can. Rate-limit login attempts per account and per IP (for example with the tower_governor crate) to slow credential stuffing. Offer password reset by emailed one-time token, never by emailing the password.

Rust A tiny login rate limiter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is SHA-256 a poor choice for storing passwords?

    Password hashes must be slow and memory-hard. General-purpose fast hashes make brute force cheap.
  2. 2. What does a per-user salt prevent?

    A unique random salt makes each hash different and forces attackers to attack every hash separately.
  3. 3. Why run Argon2 inside spawn_blocking?

    Blocking a runtime worker stalls other requests, so heavy synchronous work moves to the blocking pool.
  4. 4. A login for an unknown email should return...

    Identical responses stop attackers from discovering which emails have accounts.

Summary

  • Store only salted Argon2id hashes (PHC strings), never passwords.
  • Hash and verify inside spawn_blocking; the verify step compares in constant time.
  • Normalise emails, rely on a unique index, and map duplicates to 409.
  • Return the same 401 for unknown user and wrong password; compare against a dummy hash to even out timing.
  • Rate-limit logins and offer reset by one-time token.

Next: JWT Authentication