Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A Notes API with Authentication

Build a multi-user notes API with Axum, SQLx and JWT authentication. Plan routes and schema, enforce ownership, paginate lists and map errors, with runnable Rust stand-ins.

This project combines the whole course into one service: users register and log in, receive a token, and manage their own notes. Nobody can read or change another user's notes. It exercises extractors, state, middleware, SQLx, password hashing, JWTs, error mapping and testing.

The real crates (Axum, SQLx, jsonwebtoken, argon2) cannot run on this site, so their code is shown read-only. The parts where mistakes become vulnerabilities (ownership, token checks, pagination) are runnable Rust stand-ins.

Design

Method Path Auth Result
POST /auth/register no 201, creates a user
POST /auth/login no 200 with a token, or 401
GET /notes?limit=&after= yes the caller's notes, one page
POST /notes yes 201 with the new note
GET /notes/{id} yes the note, or 404
PUT /notes/{id} yes updated note, or 404
DELETE /notes/{id} yes 204, or 404
SQL
CREATE TABLE users (
    id            BIGSERIAL PRIMARY KEY,
    email         TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL
);

CREATE TABLE notes (
    id         BIGSERIAL PRIMARY KEY,
    owner_id   BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    title      TEXT NOT NULL,
    body       TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX notes_owner_id_idx ON notes (owner_id, id);
sequenceDiagram
    participant C as Client
    participant A as Axum
    participant D as Database
    C->>A: POST /auth/login (email, password)
    A->>D: SELECT user by email
    A->>A: verify argon2 hash, sign JWT
    A-->>C: 200 token
    C->>A: GET /notes (Authorization: Bearer token)
    A->>A: AuthUser extractor verifies token
    A->>D: SELECT notes WHERE owner_id = user
    A-->>C: 200 notes

Every protected request carries the token; the extractor turns it into a trusted user id.

The real code, in outline

An AuthUser extractor verifies the token once, so a handler that lists a user in its arguments is protected by the type system (see authentication middleware and authorization).

Rust
pub struct AuthUser { pub id: i64 }

impl FromRequestParts<AppState> for AuthUser {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, AppError> {
        let header = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok())
            .ok_or(AppError::Unauthorized)?;
        let token = header.strip_prefix("Bearer ").ok_or(AppError::Unauthorized)?;
        let claims = decode::<Claims>(token, &state.keys.decoding, &Validation::default())
            .map_err(|_| AppError::Unauthorized)?
            .claims;
        Ok(AuthUser { id: claims.sub })
    }
}

async fn get_note(
    user: AuthUser,
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Note>, AppError> {
    let note = sqlx::query_as::<_, Note>(
        "SELECT id, title, body FROM notes WHERE id = $1 AND owner_id = $2",
    )
    .bind(id)
    .bind(user.id)
    .fetch_optional(&state.pool)
    .await?
    .ok_or(AppError::NotFound)?;
    Ok(Json(note))
}

The most important line is AND owner_id = $2. Putting ownership inside the query means there is no code path that loads someone else's note and forgets to check. When the note exists but belongs to another user, answer 404, not 403, so you do not confirm that the id exists.

Stand-in: ownership checks

Rust Notes with owner checks (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.

Keyset pagination

OFFSET pagination gets slower the deeper you go and shifts when rows are inserted. Keyset pagination asks for "the next N notes after id X", which uses the index and stays stable.

Rust
#[derive(Deserialize)]
struct Page { limit: Option<i64>, after: Option<i64> }

async fn list_notes(
    user: AuthUser,
    State(state): State<AppState>,
    Query(page): Query<Page>,
) -> Result<Json<Vec<Note>>, AppError> {
    let limit = page.limit.unwrap_or(20).clamp(1, 100);
    let notes = sqlx::query_as::<_, Note>(
        "SELECT id, title, body FROM notes
         WHERE owner_id = $1 AND id > $2
         ORDER BY id LIMIT $3",
    )
    .bind(user.id)
    .bind(page.after.unwrap_or(0))
    .bind(limit)
    .fetch_all(&state.pool)
    .await?;
    Ok(Json(notes))
}

Always clamp the limit; an unbounded limit lets a client request the whole table in one call.

Rust Keyset pagination with a clamped limit (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.

Testing plan

Write oneshot tests (testing handlers) with #[sqlx::test] (test databases) for these cases: register then login; wrong password gives 401; no token gives 401; an expired token gives 401; user A creating and reading a note; user B reading A's note gives 404; pagination returns each note exactly once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why put AND owner_id = $2 inside the SQL query?

    Authorization built into the query cannot be forgotten in a later handler change.
  2. 2. A logged-in user requests a note that belongs to someone else. Which response avoids leaking information?

    A 404 hides whether the id exists at all.
  3. 3. What is the advantage of keyset pagination over OFFSET?

    It filters on an indexed column (id > after) instead of scanning past skipped rows.
  4. 4. Why clamp the limit query parameter?

    Server-side bounds protect memory and database time.

Summary

  • Design routes, auth requirements and schema before coding.
  • An AuthUser extractor makes protection a matter of a handler's argument list.
  • Enforce ownership inside every query and return 404 for other users' notes.
  • Use keyset pagination and clamp client-supplied limits.
  • Cover auth failures and cross-user access with integration tests.

Next: Axum Practice and Review