Password verify

Learn how to check a submitted password against the stored argon2 hash and answer every failure with the same generic 401

Password verification answers one question: did the person who typed this password know the password for this account? The handler fetches the stored hash for the email, runs Argon2 on the typed password with the salt and settings from that hash, and compares the result. A match means the password was right, and anything else means the answer is no. The answer for every kind of no is identical: status 401 and the body {"error": "unauthorized"}, whether the email is unknown, the account has no password, or the password is wrong.

Where This Fits

Signup stored a hash and forgot the password. This page is the other half of that deal. A client sends an email and a password to POST /login, and the handler checks them against the row signup created. The check reads the hash, never the password, and the response on success is the user, with no token and no hash attached. The route proves who is asking, and what the app does with that proof afterwards is a separate step.

Think of a doorkeeper with a list of ticket numbers. A visitor shows a ticket, the doorkeeper checks the number against the list, and the visitor is either let in or turned away. The doorkeeper never asks what coat the ticket belongs to, and never explains why a ticket failed. The number either matches or it does not, and the answer at the door is the same for every ticket that does not match.

The Smallest Working Version

This page builds on the signup project, with the same Cargo.toml, the same error type, the same pool helper, and the same main.rs. The new pieces are the verify helper in src/password.rs, the login handler in src/handlers.rs, and the second route in src/lib.rs.

src/password.rs
use argon2::{
    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
    Argon2,
};

use crate::errors::AppError;

pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|error| {
                eprintln!("password hashing failed: {error}");
                AppError::InternalError
            })
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

pub async fn verify_password(password: String, stored_hash: String) -> Result<bool, AppError> {
    tokio::task::spawn_blocking(move || {
        let parsed = match PasswordHash::new(&stored_hash) {
            Ok(parsed) => parsed,
            Err(error) => {
                eprintln!("stored password hash could not be parsed: {error}");
                return Err(AppError::InternalError);
            }
        };
        Ok(Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok())
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

verify_password returns a yes or no answer, wrapped in a Result. The bool says whether the password matched, and the Err case is reserved for a failure that is not about the password at all, like a stored hash that cannot be parsed. A wrong password is not an error in this function. It is a false, returned normally, and the handler turns it into a 401. That split matters. A wrong password is an expected outcome the handler answers, and a damaged stored value is a server fault the log must record.

src/handlers.rs
use axum::{
    Json,
    extract::State,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::{
    errors::AppError,
    password::{hash_password, verify_password},
};

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, FromRow)]
pub struct StoredUser {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub password_hash: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SignupInput {
    pub name: String,
    pub email: String,
    pub password: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_signup_input(name: &str, email: &str, password: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    if password.chars().count() < 8 {
        return Err(AppError::ValidationError(
            "password must be at least 8 characters".to_string(),
        ));
    }
    Ok(())
}

pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_signup_input(&input.name, &input.email, &input.password)?;
    let password_hash = hash_password(input.password).await?;
    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
        input.name,
        input.email,
        password_hash
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(user)))
}

pub async fn verify_login(
    State(pool): State<PgPool>,
    Json(input): Json<LoginInput>,
) -> Result<Json<User>, AppError> {
    let stored = sqlx::query_as!(
        StoredUser,
        "SELECT id, name, email, password_hash FROM users WHERE email = $1",
        input.email
    )
    .fetch_optional(&pool)
    .await?;
    let Some(stored) = stored else {
        return Err(AppError::Unauthorized);
    };
    let Some(stored_hash) = stored.password_hash else {
        return Err(AppError::Unauthorized);
    };
    let matches = verify_password(input.password, stored_hash).await?;
    if !matches {
        return Err(AppError::Unauthorized);
    }
    Ok(Json(User {
        id: stored.id,
        name: stored.name,
        email: stored.email,
    }))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;
pub mod password;

use axum::{Router, routing::post};
use handlers::{signup, verify_login};
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/signup", post(signup))
        .route("/login", post(verify_login))
        .with_state(pool)
}

Start the server against the same database the signup page used:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo run

Create an account first, then log in with the right password. The login answers 200 with the user:

curl -s -X POST http://127.0.0.1:3000/signup \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}'
curl -i -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "asha@example.com", "password": "correct horse battery staple"}'
HTTP/1.1 200 OK
content-type: application/json
content-length: 49

{"id":1,"name":"Asha","email":"asha@example.com"}

Now log in with the wrong password, and then with an email that has no account. Both answers are identical:

curl -i -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "asha@example.com", "password": "wrong password"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24

{"error":"unauthorized"}
curl -i -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "nobody@example.com", "password": "wrong password"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24

{"error":"unauthorized"}

The two failures are indistinguishable from the outside. Same status, same headers, same body, same length. A person reading the responses cannot tell whether the email exists, and that is the whole point of this page.

Working Setup:

If the right password returns 200 with the user, and the wrong password and the unknown email both return 401 with {"error": "unauthorized"}, the check is wired up correctly. All three outcomes come from one handler and one error variant.

Understanding the Handler Line by Line

The handler is short, and each of its pieces does one job. The shape to learn is the three questions it asks in order, and the single answer it gives for every no.

Fetching the stored row

    let stored = sqlx::query_as!(
        StoredUser,
        "SELECT id, name, email, password_hash FROM users WHERE email = $1",
        input.email
    )
    .fetch_optional(&pool)
    .await?;

The query selects the row by email, because the email is the unique column that identifies the account. It selects into StoredUser, the struct that holds the hash, because this handler needs the hash and the response struct does not have one. fetch_optional runs the query and returns either one row or nothing, as an Option<StoredUser>. It never fails when the email is unknown. It returns None, and the handler decides what that means. The ? at the end only handles database failures, like a lost connection, which become a 500 through the From implementation.

The query lists all four columns, including the hash, because the handler needs all four. The id, name, and email build the response on success, and the hash feeds the check. A SELECT * would also work today, and it would break the day a column is added, because the struct would gain a value it has no field for. Listing the columns keeps the query honest about what it needs.

The unknown email branch

    let Some(stored) = stored else {
        return Err(AppError::Unauthorized);
    };

The let ... else line unwraps the Option. If the query returned a row, the row is bound to the name stored and the handler carries on. If it returned None, the else block runs, and the handler returns AppError::Unauthorized at once. There is no message that says the email is unknown, no different status, and no log line naming the email. The handler treats an unknown email exactly like a wrong password, and the client sees the same 401 either way.

The null hash branch

    let Some(stored_hash) = stored.password_hash else {
        return Err(AppError::Unauthorized);
    };

The second let ... else unwraps the hash field, which is an Option<String> because the column is nullable. If the account has a hash, the string is bound to stored_hash and the handler carries on. If the column is null, the account has no password on file, and the handler returns the same Unauthorized error. The account exists, the email is real, and the answer is still the generic 401, because telling the client that the account has no password would reveal that the account exists, which is the same leak as telling them the email is unknown.

Running the check

    let matches = verify_password(input.password, stored_hash).await?;
    if !matches {
        return Err(AppError::Unauthorized);
    }

verify_password takes the typed password and the stored hash, both by value, and returns a bool. The ? handles only the server fault case, a stored hash that cannot be parsed, which becomes a 500. A wrong password is a false, and the if turns it into the same Unauthorized error as the two branches above. Three different failures, one error value, one response. The typed password was moved into the call, so no later code in the handler can read it or log it.

Building the success response

    Ok(Json(User {
        id: stored.id,
        name: stored.name,
        email: stored.email,
    }))
}

On success, the handler builds a User from the stored row, field by field, and returns it as JSON with status 200. The default status for a handler that returns Json with no status tuple is 200, which means the request succeeded. The User is built by hand instead of selected directly, because the query returned a StoredUser that holds the hash, and the response must not carry one. Constructing the three field struct is the last step that keeps the hash inside the server. The row was fetched once, used for the check, and then trimmed down to the three safe fields for the response.

The Concept Behind Verify

Verification replays the hashing with the same inputs and compares the outputs. The stored string holds the salt and the settings, so the replay needs nothing else. Argon2 runs the typed password through the same memory and time cost with the same salt, produces a 32 byte output, and compares it with the stored output. A match means the typed password was the one that produced the stored string, because only that password produces that output with that salt.

The comparison inside the crate runs in constant time, which means it takes the same time whether the guess is close or far off. A plain string comparison with == stops at the first character that differs, so a guess that matches the first ten characters takes slightly longer to reject than a guess that differs at the first character, and that timing difference can leak information about the stored value. The crate's comparison removes that leak by always comparing every byte.

Verification is also the reason the salt can sit in the stored string in plain sight. The salt is not a secret, and the attacker already has it when they have the hash. The salt's job is to make each account's hash unique, not to hide anything. Knowing the salt lets the attacker test guesses against one account, and the memory and time cost is what makes each guess expensive. The security rests on the cost, not on the secrecy of the salt.

Verification Needs Nothing Except the Stored String:

The check takes two inputs, the typed password and the stored string, and the stored string carries its own salt, settings, version, and algorithm. There is no settings lookup, no salt column, and no version check in the handler. The string is the whole record of how the password was hashed, and the handler trusts it to describe itself.

Why One Generic 401 for Every Failure

Three different things can go wrong at login, and the client is told the same thing about all three. That sameness is a security rule, and it has a name: avoid user enumeration. Enumeration is the act of working out which accounts exist by probing the system and reading the differences in its answers. An attacker who can tell a real email from a fake one can build a list of accounts and then attack that list with password guesses, phishing, or credential stuffing, which is the act of trying passwords leaked from other sites against these accounts.

A handler that answers "email not found" for an unknown email and "wrong password" for a known one hands the attacker a yes or no oracle for every email they try. They send a thousand emails, keep the ones that get the password error, and throw the rest away. The list they keep is a list of real accounts, and it cost them nothing but requests. A handler that answers 401 with {"error": "unauthorized"} for both gives them nothing to sort by. Every probe returns the same bytes, and the list they build is no better than guessing.

The rule extends to the null hash case. An account with no password is still an account, and an answer that distinguished it would reveal its existence just as surely as a different message for an unknown email. The same applies to the status code. A 404 for an unknown email and a 401 for a wrong password would leak the same fact through the number instead of the words, so the status stays 401 for all three.

// Wrong - the two messages let an attacker sort real emails from fake ones
let stored = sqlx::query_as!(StoredUser, "SELECT ... FROM users WHERE email = $1", input.email)
    .fetch_optional(&pool)
    .await?;
let Some(stored) = stored else {
    return Err(AppError::ValidationError("no account with that email".to_string()));
};
let matches = verify_password(input.password, stored_hash).await?;
if !matches {
    return Err(AppError::ValidationError("wrong password".to_string()));
}

The two messages look helpful, and they are exactly the help an attacker wants. A real user who mistypes an email gets a useful hint, and an attacker who probes a thousand emails gets a list of accounts. The helpfulness is not worth the leak. The fix is the handler on this page, where every failure returns AppError::Unauthorized, and the message is always the single word "unauthorized".

One honest caveat belongs here. The three failure paths do not take the same time. An unknown email returns at once, because there is nothing to verify, while a wrong password pays the full Argon2 cost before it fails. A careful attacker measuring response times could still tell the two apart. Evening out the timing, by running a dummy verification for unknown emails, is a further hardening step, and it is a separate piece of work from the identical responses on this page. The identical status and body close the easy leak, which is the message channel, and the timing channel is the next layer to close.

401 Means Unknown, 403 Means Refused

Status 401 means the server does not know who is asking. The word in the status name is Unauthorized, which is a confusing name, because in everyday language it sounds like permission. In HTTP it means authentication failed, and authentication is the act of proving identity. The request arrived without credentials, or with credentials the server does not accept, so the server cannot tie the request to any user at all.

Status 403 means something different. It means the server knows who is asking and refuses anyway. The identity was proven, and a rule says this user may not do this thing. A login with the wrong password is a 401, because the server still does not know who typed it. A logged in user asking for another user's settings is a 403, because the server knows exactly who is asking and says no.

The retry test tells them apart. If logging in again could fix the request, the answer is 401. If logging in again changes nothing, because the user is known and the rule still applies, the answer is 403. The login handler on this page only ever answers 401, because every failure here is a failure to prove identity, and a fresh login attempt is always a sensible next step for the client.

A 403 on a Failed Login Is the Wrong Status:

Answering a wrong password with 403 tells the client the server knows who they are, which it does not, and it tells a client program that retrying is pointless, which is false. The fix is the Unauthorized variant. Keep the retry test in mind whenever the choice comes up. If a fresh login could fix it, the answer is 401.

The Null Hash and the Damaged Hash

Two stored values deserve their own section, because they fail in different ways and the handler answers them differently on purpose.

A null hash means the account has no password. The row below was inserted directly into the database, without going through signup, so its hash column is empty:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" -c "SELECT id, name, email, password_hash FROM users WHERE email = 'nopass@example.com';"
 id | name  |       email        | password_hash
----+-------+--------------------+---------------
  2 | NoPass | nopass@example.com |

Logging in as that user answers 401, exactly like a wrong password:

curl -i -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "nopass@example.com", "password": "anything at all"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24

{"error":"unauthorized"}

A damaged hash is different. It means the column holds a value that is not a valid PHC string, which should never happen when signup is the only writer, and can happen when a row is edited by hand or a migration writes a bad value. The login check cannot parse it, and that is a server fault, not a wrong password, so the handler answers 500 and logs the cause:

curl -i -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "broken@example.com", "password": "anything at all"}'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 32

{"error":"something went wrong"}

The server log keeps the detail the client never sees:

stored password hash could not be parsed: password hash string missing field

The split is deliberate. A null hash is an expected state, an account without a password, and it gets the generic 401 like every other failed check. A damaged hash is an unexpected state, a value that should be a hash and is not, and it gets a 500, because the server cannot do its job with the data it has. The client message stays generic in both cases, and only the log tells them apart.

The Request Flow

The path of a login request through the app looks like this:

Client sends POST /login with JSON body
        |
        v
Axum parses the body into LoginInput
        |
        v
Handler selects the row by email
        |
        +-- no row --> 401 with {"error": "unauthorized"}
        |
        v
Handler checks the hash is present
        |
        +-- null hash --> 401 with {"error": "unauthorized"}
        |
        v
verify_password runs Argon2 on a blocking thread
        |
        +-- stored hash damaged --> 500 with {"error": "something went wrong"}
        |
        +-- password wrong --> 401 with {"error": "unauthorized"}
        |
        v
Handler returns 200 with the user as JSON

Every failure path except the damaged hash ends in the same response, and the diagram shows why. The three 401 branches are three ways of saying the same thing, that the server cannot tie this request to an account, and the client needs nothing more specific than that.

Testing the Verify Handler

The tests below build the router with a real pool, sign up an account, and then log in four ways: right password, wrong password, unknown email, and an account with no password. The last three must all return the exact same response.

tests/auth_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::{app, db::create_pool};
use tower::ServiceExt;

async fn router() -> axum::Router {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url).await.unwrap();
    sqlx::query!("DELETE FROM users").execute(&pool).await.unwrap();
    app(pool)
}

async fn post(router: axum::Router, uri: &str, body: &str) -> (StatusCode, String) {
    let response = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri(uri)
                .header("Content-Type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    let status = response.status();
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    (status, String::from_utf8(bytes.to_vec()).unwrap())
}

#[tokio::test]
async fn login_right_password_returns_200() {
    let r = router().await;
    let (status, _) = post(
        r.clone(),
        "/signup",
        r#"{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let (status, body) = post(
        r,
        "/login",
        r#"{"email": "asha@example.com", "password": "correct horse battery staple"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.contains("\"email\":\"asha@example.com\""));
}

#[tokio::test]
async fn login_wrong_password_unknown_email_and_null_hash_all_return_same_401() {
    let r = router().await;
    let (status, _) = post(
        r.clone(),
        "/signup",
        r#"{"name": "Asha", "email": "asha@example.com", "password": "correct horse battery staple"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url).await.unwrap();
    sqlx::query!("INSERT INTO users (name, email) VALUES ('NoPass', 'nopass@example.com')")
        .execute(&pool)
        .await
        .unwrap();
    for body in [
        r#"{"email": "asha@example.com", "password": "wrong password"}"#,
        r#"{"email": "nobody@example.com", "password": "wrong password"}"#,
        r#"{"email": "nopass@example.com", "password": "anything at all"}"#,
    ] {
        let (status, text) = post(r.clone(), "/login", body).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        assert_eq!(text, r#"{"error":"unauthorized"}"#);
    }
}

The second test is the one that guards this page. It loops over three different login attempts and asserts the exact same status and the exact same body text for all three, character for character. A future change that gave one failure a different message would fail the test, which is the point. The test needs the database, so run it with the same value the server uses:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo test -- --test-threads=1
test login_right_password_returns_200 ... ok
test login_wrong_password_unknown_email_and_null_hash_all_return_same_401 ... ok

The --test-threads=1 flag runs the tests one at a time. The tests share one table, and running them at the same time could make one test delete rows another test is reading. Serial runs keep the shared table safe. These tests were run against a live Postgres database while writing this page, and both passed.

Assert the Exact Body, Not Just the Status:

A test that checks only the status would miss a handler that returned 401 with a message naming the failure. The loop above asserts the full body text, so the message is pinned too. When a response must be identical across cases, test the bytes, not just the number.

Common Beginner Mistakes

Comparing the typed password with the stored hash

// Wrong - the typed password is plain text and the stored value is a hash
if input.password == stored_hash {
    return Ok(Json(user));
}

This never matches, because the two sides are different kinds of value, and it would be a security failure if it ever did match, because it would mean the stored value was a plain password. The fix is the verification call. Parse the stored string, run Argon2 on the typed password with the salt from the string, and compare the outputs inside the crate.

Hashing the typed password and comparing the two hashes

// Wrong - the fresh hash has a fresh salt, so the strings never match
let fresh = hash_password(input.password).await?;
if fresh == stored_hash {
    return Ok(Json(user));
}

This is the same mistake in a subtler form. The fresh hash is a valid hash of the right password, and it still differs from the stored hash, because the salt is random every time. Two hashes of the same password are never equal, and comparing them with == rejects every correct password. The fix is verify_password, which reuses the stored salt instead of generating a new one.

A Login That Rejects Every Password Points Here:

If every login fails, including one with the password that was just used at signup, the handler is almost certainly comparing hashes instead of verifying. Signup hashes with a fresh salt, login hashes with another fresh salt, and the two strings differ by design. Replace the comparison with verify_password and the logins start working.

Logging the submitted password

// Wrong - the password is now in the log file in readable form
eprintln!("login attempt for {} with password {}", input.email, input.password);

A log line like this turns the server log into a password store. Log files are copied, backed up, shipped to log services, and read by people who should never see a password, and a password in a log is as exposed as a password in a table. Log the email if the debugging needs it, log the outcome, and never log the password. The handler on this page logs nothing on a failed check, because a failed check is an expected outcome, not an event worth recording in detail.

Returning 404 for an unknown email

// Wrong - the status code leaks whether the email exists
let Some(stored) = stored else {
    return Err(AppError::NotFound);
};

A 404 says the thing asked for does not exist, and here the thing is the account behind the email. An attacker probing emails can sort the 404s from the 401s and build a list of real accounts, which is the same leak as the different messages, carried by the status code instead of the words. The fix is the handler on this page. Every failure to prove identity is a 401, and the 404 variant stays reserved for resources that genuinely do not exist.

Checking the password before fetching the row

// Wrong - there is nothing to check the password against yet
let matches = verify_password(input.password, stored_hash).await?;

This fragment has no stored_hash to work with, because the row has not been fetched. The order in the handler is fixed: fetch the row, confirm it exists, confirm it has a hash, and only then verify. Each step produces the value the next step needs, and skipping ahead leaves the next step with nothing to hold. The let ... else branches are the gates, and the verification is the last one through them.

Final Complete Example

Here is everything from this page put together: the password module, the handler file with both routes, the router, and the shared error and pool files the handler depends on.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
    Unauthorized,
    Forbidden,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
            AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/password.rs
use argon2::{
    password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
    Argon2,
};

use crate::errors::AppError;

pub async fn hash_password(password: String) -> Result<String, AppError> {
    tokio::task::spawn_blocking(move || {
        Argon2::default()
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|error| {
                eprintln!("password hashing failed: {error}");
                AppError::InternalError
            })
    })
    .await
    .map_err(|_| AppError::InternalError)?
}

pub async fn verify_password(password: String, stored_hash: String) -> Result<bool, AppError> {
    tokio::task::spawn_blocking(move || {
        let parsed = match PasswordHash::new(&stored_hash) {
            Ok(parsed) => parsed,
            Err(error) => {
                eprintln!("stored password hash could not be parsed: {error}");
                return Err(AppError::InternalError);
            }
        };
        Ok(Argon2::default()
            .verify_password(password.as_bytes(), &parsed)
            .is_ok())
    })
    .await
    .map_err(|_| AppError::InternalError)?
}
src/handlers.rs
use axum::{
    Json,
    extract::State,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::{
    errors::AppError,
    password::{hash_password, verify_password},
};

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, FromRow)]
pub struct StoredUser {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub password_hash: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SignupInput {
    pub name: String,
    pub email: String,
    pub password: String,
}

#[derive(Debug, Deserialize)]
pub struct LoginInput {
    pub email: String,
    pub password: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_signup_input(name: &str, email: &str, password: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    if password.chars().count() < 8 {
        return Err(AppError::ValidationError(
            "password must be at least 8 characters".to_string(),
        ));
    }
    Ok(())
}

pub async fn signup(
    State(pool): State<PgPool>,
    Json(input): Json<SignupInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
    check_signup_input(&input.name, &input.email, &input.password)?;
    let password_hash = hash_password(input.password).await?;
    let user = sqlx::query_as!(
        User,
        "INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email",
        input.name,
        input.email,
        password_hash
    )
    .fetch_one(&pool)
    .await?;
    Ok((StatusCode::CREATED, Json(user)))
}

pub async fn verify_login(
    State(pool): State<PgPool>,
    Json(input): Json<LoginInput>,
) -> Result<Json<User>, AppError> {
    let stored = sqlx::query_as!(
        StoredUser,
        "SELECT id, name, email, password_hash FROM users WHERE email = $1",
        input.email
    )
    .fetch_optional(&pool)
    .await?;
    let Some(stored) = stored else {
        return Err(AppError::Unauthorized);
    };
    let Some(stored_hash) = stored.password_hash else {
        return Err(AppError::Unauthorized);
    };
    let matches = verify_password(input.password, stored_hash).await?;
    if !matches {
        return Err(AppError::Unauthorized);
    }
    Ok(Json(User {
        id: stored.id,
        name: stored.name,
        email: stored.email,
    }))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;
pub mod password;

use axum::{Router, routing::post};
use handlers::{signup, verify_login};
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/signup", post(signup))
        .route("/login", post(verify_login))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

Run it with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_password" cargo run

Then check the three outcomes with:

curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "asha@example.com", "password": "correct horse battery staple"}'

Summary

The check is three questions asked in order, and one answer shape for every no. Is there a row for this email, does it hold a hash, and does the typed password reproduce the stored output. A yes to all three returns the user, and any no returns the same 401 with the same single word body. The discipline is in what the handler refuses to say. It never names which question failed, because each name would be a fact about the account list, and the account list is not the client's business. The decision to carry forward is a test to run on every login shaped response from now on. Send a wrong password, an unknown email, and an account with no password, and compare the three responses byte for byte. If they differ anywhere, the handler is leaking, and the fix is to route every failure through the one variant that says nothing except that the server does not know who is asking.