Authentication & Security
8 min read
Course: Axum
Module: Authentication & Security
Welcome back, Rustacean! π¦
If you thought ownership and borrowing were the only things guarding your memory, wait until you meet Authentication. In the web world, we can't just trust that everyone who knocks on our server's door is who they say they are. We need bouncers, ID cards, and secret vaults.
In this module, we are going to build a fortress around your Axum application. We will move from the "wild west" of public routes to a secure system using Industry Standard practices.
Table of Contents
- Securing Routes: The Concept of Auth Middleware
- JWT (JSON Web Tokens): Generating and Validating Tokens
- The Extract-Auth Pattern: Creating a Custom
RequireAuthExtractor - Password Hashing: Integrating Argon2 in User Flows
1. Securing Routes: The Concept of Auth Middleware
Definition:
Middleware is code that runs before your request hits the final handler (or after the handler finishes). Think of it as a series of checkpoints or filters.
The Problem:
Imagine you have 50 different routes (endpoints) that should only be accessed by admins.
- Without Middleware: You write an
if !is_admin { return Error }check inside every single function. This is wet (Write Everything Twice), messy, and error-prone. - With Middleware: You wrap those 50 routes in a "layer". The middleware acts like a club bouncer. It checks the ID once. If you aren't on the list, you don't even get to speak to the bartender (the handler).
How it works in Axum:
Axum uses tower middleware. The most common way to write this is using axum::middleware::from_fn.
π¨βπ» Hands-On: The "Bouncer" Middleware
Let's write a simple middleware that checks for a custom header.
use axum::{
body::Body,
http::{Request, StatusCode},
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
// 1. The Middleware Function
// It takes the Request and the "Next" middleware in the chain.
async fn auth_middleware(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
let auth_header = req.headers().get("x-secret-password");
// π΅οΈββοΈ The Bouncer Logic
match auth_header {
Some(header) if header == "open-sesame" => {
// β
Password matches! Let them through to the next handler.
let response = next.run(req).await;
Ok(response)
}
_ => {
// π Block access immediately. The handler is never called.
Err(StatusCode::UNAUTHORIZED)
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/public", get(|| async { "Hello, World!" })) // Open to everyone
.route("/secure", get(|| async { "Welcome to the VIP area!" })) // Locked
// Attach the middleware only to the routes above this layer
.route_layer(middleware::from_fn(auth_middleware));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("π Server running on port 3000");
axum::serve(listener, app).await.unwrap();
}π‘ Fun Fact: Middleware is like an onion. The request goes in through the layers, hits the core (handler), and the response comes out through the layers in reverse order.
2. JWT (JSON Web Tokens): Generating and Validating Tokens
Definition:
A JWT (pronounced "jot") is a compact, URL-safe means of representing claims to be transferred between two parties.
The Problem:
In the middleware example above, we sent a password in the header. That's dangerous! Also, if we have 1 million users, we can't check a database for a session ID on every single click. It's too slow.
The Solution:
Stateless Authentication. When a user logs in, we give them a signed "ID Card" (the JWT).
- They carry it (usually in the
Authorizationheader). - We verify the signature to ensure it hasn't been forged.
- We don't need to ask the database "Is this user logged in?". The token is the proof.
Dependencies:
Add this to your Cargo.toml:
[dependencies]
jsonwebtoken = "9"
serde = { version = "1", features = ["derive"] }π¨βπ» Hands-On: The Token Factory
We need a struct to represent the data inside the token (the Claims).
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use serde::{Serialize, Deserialize};
use std::time::{SystemTime, UNIX_EPOCH};
// 1. Define the Claims (The data inside the token)
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String, // Subject (User ID)
company: String,
exp: usize, // Expiration time (UTC timestamp)
}
const SECRET_KEY: &[u8] = b"super_secret_key_dont_share_this";
fn main() {
// --- GENERATING A TOKEN (Login) ---
let my_claims = Claims {
sub: "user_123".to_owned(),
company: "FreeCodeCamp".to_owned(),
// Expires in 1 hour
exp: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + 3600) as usize,
};
// Encode: Create the signed token
let token = encode(
&Header::default(),
&my_claims,
&EncodingKey::from_secret(SECRET_KEY)
).unwrap();
println!("π Generated JWT: {}", token);
// --- VALIDATING A TOKEN (Protected Route) ---
// Decode: Verify signature and expiration
// We strictly use the Default validation which checks 'exp' automatically
let token_data = decode::<Claims>(
&token,
&DecodingKey::from_secret(SECRET_KEY),
&Validation::new(Algorithm::HS256),
);
match token_data {
Ok(data) => println!("β
Valid! User: {}", data.claims.sub),
Err(e) => println!("β Invalid token: {}", e),
}
}β οΈ Warning: Never put sensitive data (like passwords) inside the
Claims. JWTs are signed (tamper-proof), but NOT encrypted (everyone can read them). It's like a postcard, not a sealed letter.
3. The Extract-Auth Pattern: Creating a Custom RequireAuth Extractor
The Concept:
In Axum, Extractors are the most idiomatic way to handle auth.
Instead of generic middleware, we want our handler to say: "I need an Authenticated User to run."
If the user provides a valid token, the handler runs and gets the user data immediately. If not, the handler is never called, and a 401 error is returned.
The Interface:
We implement the FromRequestParts trait for our User struct.
π¨βπ» Hands-On: The "VIP Check" Extractor
use axum::{
async_trait,
extract::FromRequestParts,
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
Json,
};
use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
use serde::{Deserialize, Serialize};
use serde_json::json;
// 1. The Error Type (What happens if auth fails?)
struct AuthError(StatusCode, String);
// Allow AuthError to be converted into a web response
impl IntoResponse for AuthError {
fn into_response(self) -> Response {
let (status, msg) = (self.0, self.1);
let body = Json(json!({ "error": msg }));
(status, body).into_response()
}
}
// 2. The struct we want in our handlers
struct AuthUser {
user_id: String,
}
// 3. The Claims (same as before)
#[derive(Debug, Deserialize)]
struct Claims {
sub: String,
exp: usize,
}
// 4. THE MAGIC: Implement FromRequestParts
#[async_trait]
impl<S> FromRequestParts<S> for AuthUser
where
S: Send + Sync,
{
type Rejection = AuthError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
// Step A: Extract the token from the "Authorization" header
let auth_header = parts
.headers
.get("Authorization")
.ok_or(AuthError(StatusCode::UNAUTHORIZED, "Missing Authorization Header".to_string()))?;
let auth_str = auth_header
.to_str()
.map_err(|_| AuthError(StatusCode::UNAUTHORIZED, "Invalid Header Format".to_string()))?;
if !auth_str.starts_with("Bearer ") {
return Err(AuthError(StatusCode::UNAUTHORIZED, "Invalid Token Scheme".to_string()));
}
let token = &auth_str[7..]; // Remove "Bearer " prefix
// Step B: Validate the token using jsonwebtoken
let token_data = decode::<Claims>(
token,
&DecodingKey::from_secret(b"super_secret_key_dont_share_this"),
&Validation::new(Algorithm::HS256),
)
.map_err(|e| AuthError(StatusCode::UNAUTHORIZED, format!("Invalid Token: {}", e)))?;
// Step C: Return the struct!
Ok(AuthUser {
user_id: token_data.claims.sub,
})
}
}
// 5. Usage in a Handler
// Notice how clean the signature is!
async fn protected_handler(user: AuthUser) -> Json<String> {
Json(format!("Hello User {}, you are authorized!", user.user_id))
}Why is this better than Middleware?
- Type Safety: The handler guarantees
userexists. You don't have to fetch it fromreq.extensions().get(). - Granularity: You can apply this to specific arguments in specific handlers.
4. Password Hashing: Integrating Argon2 in User Flows
Definition:
Hashing turns data into a fixed-size string of characters. It is a one-way process. You cannot "decrypt" a hash.
The Problem:
You should NEVER store passwords in plain text.
- Bad: Storing "password123".
- Bad: Storing MD5("password123"). Computers are too fast now; they can guess MD5 hashes in seconds.
- Good: Argon2. It is a memory-hard algorithm. It intentionally takes time and memory to compute, making it impossible for hackers to brute-force millions of passwords quickly.
Dependencies:
[dependencies]
argon2 = "0.5"
rand_core = { version = "0.6", features = ["std"] }π¨βπ» Hands-On: The Vault
This logic usually lives in your "Registration" (Hash) and "Login" (Verify) handlers.
use argon2::{
password_hash::{
rand_core::OsRng,
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
},
Argon2
};
fn main() {
let password = b"hunter42"; // The user's input
// --- REGISTRATION (Hashing) ---
// 1. Generate a random Salt
// A salt ensures that two users with the same password have different hashes.
let salt = SaltString::generate(&mut OsRng);
// 2. Hash the password
let argon2 = Argon2::default();
let password_hash = argon2.hash_password(password, &salt).unwrap().to_string();
println!("πΎ Store this in DB: {}", password_hash);
// Format looks like: $argon2id$v=19$m=4096,t=3,p=1$somesalt...$somehash...
// --- LOGIN (Verification) ---
let login_attempt = b"hunter42";
let stored_hash_from_db = &password_hash; // Fetch this from your DB
// 3. Parse the stored hash
let parsed_hash = PasswordHash::new(stored_hash_from_db).unwrap();
// 4. Verify
let is_valid = argon2.verify_password(login_attempt, &parsed_hash).is_ok();
if is_valid {
println!("π Access Granted: Generating JWT now...");
} else {
println!("π Access Denied");
}
}π§ Analogy: Hashing is like turning a steak into ground beef. You can tell the ground beef came from a cow, but no matter how hard you try, you can't turn it back into a steak.
Summary & Best Practices
We have built a complete security lifecycle:
- Registration: User sends password -> Server hashes with Argon2 -> Save to DB.
- Login: User sends password -> Server verifies with Argon2 -> Server generates JWT.
- Access: User sends JWT in header -> Axum Extractor validates signature -> Handler runs.
Pro Tips:
- HTTPS: None of this matters if you don't use HTTPS (TLS). Without it, the JWT is sent in plain text over the wire.
- Secrets: Never hardcode secrets in your code (like we did here for demo). Use environment variables (
dotenvcrate). - Expiration: Keep JWT expiration short (e.g., 15 mins) and use "Refresh Tokens" for long sessions.
π References & Resources
Happy Coding and Stay Secure! π
Challenge
Challenge Instructions
Write a JavaScript function named processUserData that takes one argument: an array of user objects.
Each user object in the input array will have the following structure:
id: numberfirstName: stringlastName: stringemail: stringage: numberisActive: booleanyearsOfExperience: number
Your function must perform the following operations in sequence using array methods:
- Filter the array to include only users who are
isActive. - From the result of the first step, further filter the array to include only users who are 18 years of age or older.
- Map the resulting filtered array to a new array of objects. Each new object should have the following structure:
{ fullName: 'FirstName LastName', email: 'user.email' }. - Using the array from step 2 (after filtering, but before mapping), calculate the total
yearsOfExperiencefor all users in that array. - The function should return a single object with two properties:
processedUsers: The array of mapped user objects from step 3.totalExperience: The total years of experience calculated in step 4.
Expected result
Your processUserData function should return a single object. When called with the provided users array, the object should have the following structure and values:
{
"processedUsers": [
{ "fullName": "John Doe", "email": "[email protected]" },
{ "fullName": "Jane Smith", "email": "[email protected]" },
{ "fullName": "Chris Lee", "email": "[email protected]" },
{ "fullName": "Michael Davis", "email": "[email protected]" }
],
"totalExperience": 18
}