JWT login handler
Learn how a POST login handler checks an email and password against the database and returns a signed JWT when they match
A login handler is the front door of a token-based API. A client sends an email and a password to one route, the handler looks the user up in the database, checks the password against the stored hash, and on success hands back a signed token. That token is the proof the client shows on later requests, so the client never has to send its password again. One route, one check, one token back.
Where This Fits
The password check from the earlier step decides whether the password matches the stored hash. This page takes that answer and turns it into something the client can carry. A successful check mints a token, a failed check answers with the same generic 401 every time, and the handler never says which part failed.
Think of a hotel front desk. A guest states a name and shows an ID, the clerk checks the register, and on a match hands over a room key. The key is not the ID, and the guest does not show the ID again at the room door. The key opens the door on its own. The email and password are the ID, the database is the register, and the token is the room key.
The Smallest Working Version
Create a project with these files. It has one route, POST /login, and nothing else.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
argon2 = "0.6"
thiserror = "2.0"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
The jsonwebtoken line needs a crypto backend feature, because version 12 does not pick one for you. rust_crypto is the pure Rust backend, so it builds with no C compiler and no extra tools. The other backend is aws_lc_rs, and the two cannot be enabled together. The tower dev-dependency is only for the tests near the end of this page.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).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
}
}
}
}
impl From<std::io::Error> for AppError {
fn from(error: std::io::Error) -> Self {
eprintln!("io error: {error}");
AppError::InternalError
}
}
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
eprintln!("json error: {error}");
AppError::InternalError
}
}
pub type HandlerResult<T> = Result<T, AppError>;
This is the shared error type for the whole app. The variant this page leans on is Unauthorized, which becomes status 401 with the body {"error": "unauthorized"}. The From implementation for sqlx::Error turns a missing row into NotFound and every other database failure into InternalError, with the detail written to the server log. The handler on this page never lets a database error reach the client as a 401, because a database failure is not an authentication failure.
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
}
use std::time::{SystemTime, UNIX_EPOCH};
use argon2::{
Argon2,
password_hash::{PasswordVerifier, phc::PasswordHash},
};
use jsonwebtoken::{EncodingKey, Header, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Deserialize)]
pub struct LoginInput {
pub email: String,
pub password: String,
}
#[derive(Debug, Serialize)]
pub struct LoginResponse {
pub token: String,
}
pub fn password_matches(password: &str, stored_hash: &str) -> bool {
let Ok(parsed_hash) = PasswordHash::new(stored_hash) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok()
}
fn expiry_in_one_hour() -> usize {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time is before the Unix epoch")
.as_secs() as usize;
now + 3600
}
pub fn create_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: expiry_in_one_hour(),
};
let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
eprintln!("encoding key error: {error}");
AppError::InternalError
})?;
encode(&Header::default(), &claims, &key).map_err(|error| {
eprintln!("token encode error: {error}");
AppError::InternalError
})
}
Claims is the data the token carries: sub holds the user id, role holds the role string, and exp holds the expiry time as seconds since the Unix epoch. A claim is a named piece of data inside a token, and these three are the whole payload this app uses. LoginInput is the JSON body the client sends, and LoginResponse is the JSON body the handler sends back, with one field, the token string.
password_matches is a small helper that answers one question with a true or false. It parses the stored hash string, and if the string is not a valid hash at all, it returns false rather than failing, because a broken stored hash can never match a password. Otherwise it asks argon2 to verify the password against the parsed hash, and returns whether that check passed. The helper takes the password as text and the stored hash as text, and it never returns the hash itself.
create_token builds the claims and signs them. expiry_in_one_hour reads the current time as seconds since the Unix epoch, which is midnight on 1 January 1970, and adds 3600, which is the number of seconds in one hour. The token therefore stops working one hour after it is made. EncodingKey::from_secret turns the secret bytes into a signing key, and in jsonwebtoken 12 it returns a Result, so the map_err turns a key failure into an internal error and the ? returns it early. encode takes the default header, the claims, and the key, and produces the token string, with any signing failure mapped the same way.
use axum::{Json, extract::State};
use sqlx::{FromRow, PgPool};
use crate::{
auth::{LoginInput, LoginResponse, create_token, password_matches},
errors::{AppError, HandlerResult},
};
#[derive(Debug, FromRow)]
pub struct LoginRow {
pub id: i32,
pub password_hash: Option<String>,
}
pub async fn login(
State(pool): State<PgPool>,
Json(input): Json<LoginInput>,
) -> HandlerResult<Json<LoginResponse>> {
let row = sqlx::query_as!(
LoginRow,
"SELECT id, password_hash FROM users WHERE email = $1",
input.email
)
.fetch_optional(&pool)
.await?;
let Some(row) = row else {
return Err(AppError::Unauthorized);
};
let Some(stored_hash) = row.password_hash else {
return Err(AppError::Unauthorized);
};
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::Unauthorized);
}
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let token = create_token(row.id, "user", &secret)?;
Ok(Json(LoginResponse { token }))
}
LoginRow holds exactly what the query returns: the id and the stored hash. The hash is an Option<String>, a value that may be present or absent, because the column is nullable, and a user with no hash has no password to check. The handler runs four steps in order: look the user up, take the stored hash, check the password, mint the token. Each failure step returns the same unauthorized variant, and the steps are explained one by one below.
pub mod auth;
pub mod db;
pub mod errors;
pub mod handlers;
use axum::{Router, routing::post};
use handlers::login;
use sqlx::PgPool;
pub fn app(pool: PgPool) -> Router {
Router::new()
.route("/login", post(login))
.with_state(pool)
}
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();
}
Before running the server, create the table and add the password column. The users table holds four columns, and the password hash lives in a fifth column added afterwards, because the table was created before passwords existed. The column is nullable, so existing rows stay valid with no hash until a password is set for them.
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" -c "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" -c "ALTER TABLE users ADD COLUMN password_hash TEXT;"
Seed one user to log in as. The hash below is the stored argon2 hash for the password ada-secret-password, made by the hashing step, and it is safe to show here because the password is a throwaway test password and the secret is a test secret. Never paste a real user's hash into documentation.
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" -c "INSERT INTO users (name, email, password_hash) VALUES ('Ada', 'ada@example.com', '\$argon2id\$v=19\$m=19456,t=2,p=1\$NoIActzZMiTufomvdfZVDw\$lOaudRKFtHKoaIWvs+f6t9fGhoVxLxvfprVT+ysFBAU') RETURNING id, name, email;"
id | name | email
----+------+-----------------
1 | Ada | ada@example.com
Also add a user with no password at all, to see what login does with a null hash:
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" -c "INSERT INTO users (name, email) VALUES ('NoPass', 'nopass@example.com') RETURNING id, name, email;"
Start the server with the database URL and the signing secret in the environment. JWT_SECRET is an environment variable, a named value set outside the program that the program reads at startup, and it holds the secret used to sign tokens. The value below is a test secret for local development only, and it must never be used anywhere real.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" JWT_SECRET="test-secret-only-for-local-development" cargo run
The terminal prints Server running at http://127.0.0.1:3000 and waits. In a second terminal, send a login request with the right password:
curl -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": "ada-secret-password"}'
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ.Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc"}
The response is status 200 with one field, the token. The token is a long string of three parts separated by dots, and the client stores it and sends it back on later requests. The exact string changes on every login, because the expiry time inside it changes, but the shape is always the same.
Working Setup:
If the login with the right password returns 200 and a JSON object with a token field, the handler works end to end. The row was found, the password matched the stored hash, and the token was signed with the secret from the environment.
Understanding the Handler Step by Step
The handler is short, and each of its steps guards the next one. A request that fails any step stops there, and the client sees the same answer for every kind of failure.
Looking the user up by email
let row = sqlx::query_as!(
LoginRow,
"SELECT id, password_hash FROM users WHERE email = $1",
input.email
)
.fetch_optional(&pool)
.await?;
The query selects the id and the stored hash for the row whose email matches the one the client sent. $1 is a placeholder, a numbered slot in the SQL string that sqlx fills with the value listed after the string, and using a placeholder instead of building the SQL by hand keeps an email with a quote in it from breaking the query. fetch_optional runs the query and returns an Option, which is either one row or nothing, because the email might not belong to anyone. query_as! checks the SQL against the real database at compile time, so DATABASE_URL must be set when running cargo check as well as cargo run.
The ? at the end turns a database failure into an early return. A database failure here becomes an internal error through the From implementation, not a 401, because the database failing is a server problem and the client cannot fix it by logging in again.
The unknown email answer
let Some(row) = row else {
return Err(AppError::Unauthorized);
};
This is the first of the three identical answers. When no row matches the email, the handler returns the unauthorized variant at once, without doing any more work. The response is 401 with the body {"error": "unauthorized"}, and it says nothing about whether the email exists. That silence is deliberate, and the section below explains why it matters.
The null hash answer
let Some(stored_hash) = row.password_hash else {
return Err(AppError::Unauthorized);
};
A user can exist with no password hash, because the column is nullable. Such a user cannot log in with a password, because there is nothing to check the password against. The handler treats that case exactly like a wrong password: the same unauthorized variant, the same body, the same status. The let ... else shape makes the intent plain. If there is no hash, stop here.
Checking the password
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::Unauthorized);
}
password_matches parses the stored hash and asks argon2 to verify the password the client sent. Argon2 is a password hashing function, a deliberately slow calculation that turns a password into a hash string, and verification repeats that calculation with the salt and parameters stored inside the hash string and compares the result. The comparison happens inside the crate, and the handler only sees a true or false. A wrong password returns the same unauthorized variant as an unknown email, so the client cannot tell the two apart.
Never Compare Passwords With ==:
A plain string comparison of the password against the stored value would only work if the stored value were the password itself, and storing plain passwords is never acceptable. The stored value is a hash, and only the argon2 verify call knows how to check a password against it. If the code ever compares input.password directly to anything from the database, the check is wrong.
Reading the secret and minting the token
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let token = create_token(row.id, "user", &secret)?;
Ok(Json(LoginResponse { token }))
The secret is read only after the password has passed, so a failed login never touches the signing key. If the environment variable is missing, the handler returns an internal error, because the server is misconfigured and no login can succeed until the secret is set. That failure is a 500, not a 401, because the user did nothing wrong. create_token builds the claims with the user id, the role "user", and an expiry one hour ahead, then signs them. Every login on this page issues the role "user", because the users table has no role column to read a role from. A role that varies per user needs a column to store it in, and that column does not exist here.
The handler returns the token wrapped in LoginResponse as JSON, with status 200. There is no cookie, no session row, and nothing stored server-side. The token itself is the proof, and the server verifies it from scratch on each later request.
Why One Answer Covers Every Failure
Three different things can go wrong, an unknown email, a user with no hash, and a wrong password, and the handler answers all three with the same 401 and the same body. That sameness is a security decision, not laziness. A response that says "no such user" for one failure and "wrong password" for another lets anyone probe which email addresses have accounts. An attacker can try a list of emails, keep the ones that get "wrong password", and throw away the ones that get "no such user", and after that the attacker owns a confirmed list of accounts to attack further.
One generic answer closes that probe. Every failed login looks identical from the outside, so trying an email teaches the attacker nothing about whether the account exists. The detail still exists, but it lives in the server log, where the person running the server can read it, not in the response, where anyone can read it. A login that fails because the database is down is the exception, and it answers 500 instead, because that failure is about the server, not about the credentials, and no attacker learns account names from it.
Different Messages Leak Accounts:
Returning a distinct message for an unknown email, such as "user not found", or for a wrong password, such as "incorrect password", turns the login route into an account checker. Keep one variant, one status, and one body for every credential failure. The rule has a name in security work, avoiding user enumeration, and it applies to signup as well as login.
The Concept Behind a Token Instead of a Session
A session keeps state on the server. The server writes a row or a cache entry when the user logs in, hands the client a random session id, and looks that id up on every request. A token keeps no state on the server. The server signs a small piece of data and hands the whole thing to the client, and on each later request it checks the signature and reads the data straight out of the token. The client carries the proof, and the server carries nothing between requests.
That difference is why the login handler stores nothing after minting the token. There is no session row to write, no cache entry to expire, and no lookup to do later. The cost is that the token cannot be taken back early. Once issued, it works until its expiry time passes, even if the user changes their password in between, because the server has no list of live tokens to cross a name off. The expiry of one hour is the compromise that bounds that cost: a stolen token stops working on its own, an hour after it was made.
A beginner can think of the difference as a coat check ticket versus a stamp on the hand. A coat check ticket means nothing on its own, and the attendant must look up the number to find the coat. A stamp on the hand carries its own meaning, and any doorkeeper who knows what the stamp looks like can check it without a list. The token is the stamp, and the signature is what makes the stamp hard to forge.
A Richer Complete Example
The smallest version shows the happy path. The same server shows the failure paths too, and they are the ones that prove the design. Run these four requests against the running server.
The right password returns a token:
curl -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": "ada-secret-password"}'
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ.Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc"}
The wrong password returns the generic 401:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": "wrong-password"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
An email nobody owns returns exactly the same answer, byte for byte:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ghost@example.com", "password": "ada-secret-password"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
The user with no stored hash returns the same answer again:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "nopass@example.com", "password": "anything"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
All three failures are indistinguishable in the response, which is the point. A client that receives any of them shows the same message to the user, and an attacker probing the route learns nothing.
What Happens With a Broken Request Body
The handler body never runs when the JSON itself is broken, because the Json extractor rejects the request first. A body that is not valid JSON gets a 400 with a plain text explanation:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": }'
HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
Failed to parse the request body as JSON: password: expected value at line 1 column 42
A body that is valid JSON but missing the password field gets a 422, also as plain text:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com"}'
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
Failed to deserialize the JSON body into the target type: missing field `password` at line 1 column 28
These two answers look different from the shared JSON error shape, because they come from the extractor, not from the handler. The handler never sees these requests, so the shared AppError shape never applies to them. That split is normal. The extractor guards the shape of the request, and the handler guards the credentials inside a well-shaped request.
What Happens When the Secret Is Missing
Starting the server without JWT_SECRET set lets the server start, because nothing reads the secret at startup. The first login with the right password then fails, after the password check has already passed:
curl -i -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": "ada-secret-password"}'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 32
{"error":"something went wrong"}
The 500 is correct here. The credentials were right, and the server could not finish the job because its own configuration is incomplete. The fix is to set the variable and restart the server. The password check running before the secret read is also why the failure arrives late: the handler only discovers the missing secret after it has already decided the user may log in.
The Secret Is Read Per Login:
The handler reads JWT_SECRET from the environment on every successful login, rather than once at startup. That keeps the example simple and makes the missing-secret failure easy to see, and it means changing the secret takes effect on the next login without a restart. A larger app usually reads the secret once at startup and stores it in shared state, so a missing secret fails fast before serving any request.
A Plain Text Diagram of the Flow
The request passes through the checks in order, and every failure leaves by the same exit.
client sends POST /login with email and password
|
v
Json parses the body into LoginInput
|
v
SELECT id, password_hash FROM users WHERE email = $1
|
+-- no row --> 401 + {"error": "unauthorized"}
|
v
row has a stored hash?
|
+-- hash is null --> 401 + {"error": "unauthorized"}
|
v
argon2 verifies the password
|
+-- no match --> 401 + {"error": "unauthorized"}
|
v
read JWT_SECRET, sign the claims
|
+-- secret missing --> 500 + {"error": "something went wrong"}
|
v
200 + {"token": "..."}
The diagram has three exits that look the same and one that looks different. The three identical exits are credential failures, and the one different exit is a server failure. Keeping those two kinds apart is what makes the client able to tell the user "try again" for one and "something is broken" for the other.
Testing It
The tests below send requests through the router with oneshot, a method from tower::ServiceExt that sends one request directly through the router with no network involved. They run against a real database, because the handler is mostly a database lookup, and testing it against a fake would test the fake, not the handler. Set the same two environment variables the server uses, and run the tests one at a time so they do not share the table in parallel.
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();
app(pool)
}
async fn post_login(router: axum::Router, body: &str) -> (StatusCode, String) {
let response = router
.oneshot(
Request::builder()
.method("POST")
.uri("/login")
.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_with_right_password_returns_token() {
let (status, body) = post_login(
router().await,
r#"{"email": "ada@example.com", "password": "ada-secret-password"}"#,
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(body.contains("\"token\":\"eyJ"));
}
#[tokio::test]
async fn login_with_wrong_password_is_unauthorized() {
let (status, body) = post_login(
router().await,
r#"{"email": "ada@example.com", "password": "wrong-password"}"#,
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn login_with_unknown_email_is_unauthorized() {
let (status, body) = post_login(
router().await,
r#"{"email": "ghost@example.com", "password": "ada-secret-password"}"#,
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn login_with_null_hash_is_unauthorized() {
let (status, body) = post_login(
router().await,
r#"{"email": "nopass@example.com", "password": "anything"}"#,
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
The shared post_login helper builds the request and returns the status and body text, so each test stays short. The right-password test checks that the body contains a token starting with eyJ, which is the base64 encoding of {"typ", the first bytes of every token this app mints. The three failure tests assert the exact body, because the exact body is the design decision. If somebody later changes the handler to say which failure happened, those tests fail, which forces the change to be deliberate rather than accidental.
Run them with:
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" JWT_SECRET="test-secret-only-for-local-development" cargo test --test jwt_test -- --test-threads=1
test login_with_null_hash_is_unauthorized ... ok
test login_with_right_password_returns_token ... ok
test login_with_unknown_email_is_unauthorized ... ok
test login_with_wrong_password_is_unauthorized ... 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 read rows another test is changing. Serial runs keep the shared table safe.
Common Beginner Mistakes
Telling the client which part failed
// Wrong - the two messages let an attacker list real accounts
let Some(row) = row else {
return Err(AppError::ValidationError("no such user".to_string()));
};
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::ValidationError("wrong password".to_string()));
}
Two problems sit in this version. The messages name the failure, which is the enumeration leak described above, and the variant is wrong, because a failed login is not a validation failure, so the status would be 422 instead of 401. The fix is the unauthorized variant with its single generic word for every credential failure.
Checking the password before looking the user up
// Wrong - there is no stored hash yet, so there is nothing to check against
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::Unauthorized);
}
let row = sqlx::query_as!(LoginRow, "SELECT id, password_hash FROM users WHERE email = $1", input.email)
.fetch_optional(&pool)
.await?;
The password check needs the stored hash, and the stored hash comes from the row, so the lookup must come first. The order is lookup, then hash, then password, then token, and no step can move earlier than the step that produces its input. A handler that checks the password first has to invent a hash to check against, and any invented hash makes the check meaningless.
Returning the user row on a failed login
// Wrong - a failed login must not hand back the row it found
let Some(row) = row else {
return Err(AppError::Unauthorized);
};
if !password_matches(&input.password, &stored_hash) {
return Ok(Json(json!({ "id": row.id, "email": input.email })));
}
A failed login returns nothing but the error. Handing back the id or the email of the account that failed to log in gives an attacker confirmed account details for free, and it gives the client data it has no right to yet. The error variant is the whole response.
Minting the token before checking the password
// Wrong - the token is made before the caller is known
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let token = create_token(row.id, "user", &secret)?;
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::Unauthorized);
}
Ok(Json(LoginResponse { token }))
This version builds a valid token for a user whose password has not been checked yet, and returns it only when the password passes, so the visible behaviour looks the same. The waste is the problem: signing work runs for every failed login, and the code reads as if the token existed before the caller earned it. A future edit that moves the early return could leak the token. Mint the token last, after every check has passed, so the code cannot hand out a token to an unchecked caller.
Storing the plain password in the token
// Wrong - the token leaves the server, and anyone who reads it reads the password
let claims = Claims {
sub: row.id,
role: "user".to_string(),
exp: expiry_in_one_hour(),
};
This version is actually the correct claims shape, and the mistake it guards against is adding a password field to it. A token is readable by anyone who holds it, because its payload is only encoded, not encrypted, so anything put inside it is visible to the client and to anyone the client shows it to. The claims hold an id, a role, and an expiry, and nothing secret. A password, an email, or a secret key must never appear in a claim.
Checking That Everything Compiles
Before running cargo run, run cargo check. The query_as! macro needs the database at compile time, so DATABASE_URL must be set for the check as well as for the run:
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" cargo check
If the output ends with a Finished line and no errors, there are no type errors, and the SQL passed the compile-time check against the real table. Then run the server with both variables set, as shown above.
Final Complete Example
Here is everything from this page put together. The project has one route, one handler, and the shared auth, error, and pool files.
use std::time::{SystemTime, UNIX_EPOCH};
use argon2::{
Argon2,
password_hash::{PasswordVerifier, phc::PasswordHash},
};
use jsonwebtoken::{EncodingKey, Header, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Deserialize)]
pub struct LoginInput {
pub email: String,
pub password: String,
}
#[derive(Debug, Serialize)]
pub struct LoginResponse {
pub token: String,
}
pub fn password_matches(password: &str, stored_hash: &str) -> bool {
let Ok(parsed_hash) = PasswordHash::new(stored_hash) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok()
}
fn expiry_in_one_hour() -> usize {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time is before the Unix epoch")
.as_secs() as usize;
now + 3600
}
pub fn create_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: expiry_in_one_hour(),
};
let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
eprintln!("encoding key error: {error}");
AppError::InternalError
})?;
encode(&Header::default(), &claims, &key).map_err(|error| {
eprintln!("token encode error: {error}");
AppError::InternalError
})
}
use axum::{Json, extract::State};
use sqlx::{FromRow, PgPool};
use crate::{
auth::{LoginInput, LoginResponse, create_token, password_matches},
errors::{AppError, HandlerResult},
};
#[derive(Debug, FromRow)]
pub struct LoginRow {
pub id: i32,
pub password_hash: Option<String>,
}
pub async fn login(
State(pool): State<PgPool>,
Json(input): Json<LoginInput>,
) -> HandlerResult<Json<LoginResponse>> {
let row = sqlx::query_as!(
LoginRow,
"SELECT id, password_hash FROM users WHERE email = $1",
input.email
)
.fetch_optional(&pool)
.await?;
let Some(row) = row else {
return Err(AppError::Unauthorized);
};
let Some(stored_hash) = row.password_hash else {
return Err(AppError::Unauthorized);
};
if !password_matches(&input.password, &stored_hash) {
return Err(AppError::Unauthorized);
}
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::InternalError)?;
let token = create_token(row.id, "user", &secret)?;
Ok(Json(LoginResponse { token }))
}
pub mod auth;
pub mod db;
pub mod errors;
pub mod handlers;
use axum::{Router, routing::post};
use handlers::login;
use sqlx::PgPool;
pub fn app(pool: PgPool) -> Router {
Router::new()
.route("/login", post(login))
.with_state(pool)
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
argon2 = "0.6"
thiserror = "2.0"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with:
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" JWT_SECRET="test-secret-only-for-local-development" cargo run
Then log in with:
curl -X POST http://127.0.0.1:3000/login \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.com", "password": "ada-secret-password"}'
Summary
The login handler is a pipeline with a strict order and a single voice for failure. Look the user up, take the stored hash, check the password, and only then mint the token. Three different failures answer with the same 401, because the answer must not teach anyone which accounts exist. A database failure and a missing secret answer 500 instead, because those are server problems and the user cannot fix them by trying again.
The decision to carry forward is the order itself. Every step earns the next one: the lookup earns the hash, the hash earns the password check, the password check earns the token. A handler that reorders those steps either checks against nothing or hands out a token before the caller is known. Keep the order, keep one generic answer for credential failures, and the route stays both usable and closed to probing. The token it returns is the subject of the ideas that follow it: what it carries inside, how it is signed, and how the server checks it on the way back in.