Learn Actix Web · 9/13

Authentication and Security

8 min read

Hello, developer. Welcome to Step 9 of the Actix Web curriculum. 🛡️

Until now, we have built open APIs. Anyone with a URL could access your data. In the real world, this is rarely acceptable. Today, we enter the fortress of Authentication (identifying who a user is) and Authorization (determining what they are allowed to do).

This is a domain where precision is mandatory. In security, "almost correct" is effectively "wrong." We will approach this with academic rigor, ensuring you understand the underlying mechanics before writing a single line of code.


Prerequisites: Dependencies

Before we begin, we need to equip our Cargo.toml with the industry-standard crates for cryptography and session management.

toml
[dependencies]
actix-web = "4"
serde = { version = "1.0", features = ["derive"] }
# For JSON Web Tokens
jsonwebtoken = "9"
# For Password Hashing (Industry Standard)
argon2 = "0.5"
# For Randomization (Salts)
rand = "0.8"
# For Session Management
actix-identity = "0.8"
actix-session = { version = "0.10", features = ["cookie-session"] }
# Async runtime
tokio = { version = "1", features = ["full"] }

1. Implementing JWT (JSON Web Tokens) Authentication

Definition & Problem

The Problem: The HTTP protocol is stateless. When a user logs in, the server sends a response. If the user makes a second request, the server has already forgotten who they are. We need a way to verify identity on every request without sending the password every time.

The Solution: A JSON Web Token (JWT). Think of a JWT as a stamped passport. The user logs in once; you stamp a JSON document with a cryptographic signature and hand it to them. They show this passport for every subsequent request. Because you hold the private key used to sign it, you know if the passport is valid or if it has been forged.

The Anatomy of a JWT

A JWT consists of three parts separated by dots (.):

  1. Header: The algorithm used (e.g., HS256).
  2. Payload (Claims): The data (User ID, Expiration).
  3. Signature: The verification proof.

Implementation

First, let's define the Claims struct. This is the data inside the passport.

rust
use serde::{Deserialize, Serialize};
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use chrono::{Utc, Duration};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String, // Subject (usually user_id)
    exp: usize,  // Expiration time (epoch)
    iat: usize,  // Issued at
}

// ⚠️ SECURITY NOTE: Never hardcode secrets in production. 
// Use std::env::var("JWT_SECRET") instead.
const JWT_SECRET: &[u8] = b"super_secret_key_please_change_me";

pub fn create_jwt(user_id: &str) -> Result<String, jsonwebtoken::errors::Error> {
    let expiration = Utc::now()
        .checked_add_signed(Duration::hours(24))
        .expect("valid timestamp")
        .timestamp();

    let claims = Claims {
        sub: user_id.to_owned(),
        iat: Utc::now().timestamp() as usize,
        exp: expiration as usize,
    };

    let header = Header::new(Algorithm::HS256);
    
    // EncodingKey creates the signature
    encode(&header, &claims, &EncodingKey::from_secret(JWT_SECRET))
}

pub fn verify_jwt(token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
    let validation = Validation::new(Algorithm::HS256);
    
    // DecodingKey verifies the signature
    let token_data = decode::<Claims>(
        token, 
        &DecodingKey::from_secret(JWT_SECRET), 
        &validation
    )?;
    
    Ok(token_data.claims)
}

Fun Fact: The concept of a "password" dates back to Roman times, used by sentries for challenge-response identification. However, the first computer password was introduced at MIT in 1961 for the CTSS system. A software bug in 1962 caused the system to print out the master password file, marking the world's first password leak. 📜


2. Protecting Routes with Identity and Session Middleware

Definition & Problem

The Problem: While you can manually check the JWT on every function, that leads to code duplication. Furthermore, where do you store the token? LocalStorage is vulnerable to XSS (Cross-Site Scripting).

The Solution: Middleware. Middleware acts as a gatekeeper. It intercepts requests before they reach your handler. We will use actix-identity combined with actix-session. This allows us to store an encrypted session cookie containing our authentication state (or the JWT itself).

Implementation

We need to wrap our App with IdentityMiddleware and SessionMiddleware.

rust
use actix_web::{web, App, HttpServer, HttpResponse, Responder, HttpMessage};
use actix_identity::{Identity, IdentityMiddleware};
use actix_session::{SessionMiddleware, storage::CookieSessionStore};
use actix_web::cookie::Key;

async fn login(req: actix_web::HttpRequest) -> impl Responder {
    // In a real app, you would validate credentials first!
    // attach the identity to the request extension
    actix_identity::Identity::login(&req.extensions(), "user_id_123".to_owned()).unwrap();
    HttpResponse::Ok().body("Logged in!")
}

async fn logout(user: Identity) -> impl Responder {
    user.logout();
    HttpResponse::Ok().body("Logged out!")
}

async fn secret_handler(user: Identity) -> impl Responder {
    // If we reach here, the Identity extractor has already verified the user exists
    format!("Hello, {}! You found the secret.", user.id().unwrap())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Generate a random key for encryption. 
    // In production, load this from ENV to persist sessions across restarts.
    let secret_key = Key::generate();

    HttpServer::new(move || {
        App::new()
            // 1. Install Identity Middleware (Manages the identity logic)
            .wrap(IdentityMiddleware::default())
            // 2. Install Session Middleware (Manages the storage/cookie)
            .wrap(
                SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
                    .cookie_secure(false) // Set to true if using HTTPS
                    .build()
            )
            .route("/login", web::post().to(login))
            .route("/logout", web::post().to(logout))
            .route("/secret", web::get().to(secret_handler))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Note: The order of .wrap() matters! The middleware added last is executed first. Here, the Session middleware runs first (to decode the cookie), then Identity middleware runs (to look inside the session for an ID).


3. Password Hashing Integration (Argon2)

Definition & Problem

The Problem: Storing passwords in plain text is a cardinal sin. If your database is compromised, every user is compromised. Even older hashing methods like MD5 or SHA1 are now easily broken by modern GPUs.

The Solution: Argon2. Winner of the Password Hashing Competition (PHC) in 2015. It is memory-hard, meaning it requires significant RAM to compute, making it resistant to GPU/ASIC brute-force attacks.

Implementation

We will use the argon2 crate to hash a password with a random "salt" (random data added to the password to ensure that two identical passwords result in different hashes).

rust
use argon2::{
    password_hash::{
        rand_core::OsRng,
        PasswordHash, PasswordHasher, PasswordVerifier, SaltString
    },
    Argon2
};

pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
    let salt = SaltString::generate(&mut OsRng);
    let argon2 = Argon2::default();
    
    // Hash password to PHC string ($argon2id$v=19$...)
    let password_hash = argon2.hash_password(password.as_bytes(), &salt)?.to_string();
    
    Ok(password_hash)
}

pub fn verify_password(hash: &str, password: &str) -> bool {
    let parsed_hash = match PasswordHash::new(hash) {
        Ok(h) => h,
        Err(_) => return false,
    };
    
    // Argon2::default() automatically picks up parameters from the hash string
    Argon2::default().verify_password(password.as_bytes(), &parsed_hash).is_ok()
}

// Example Usage
fn main_hash_example() {
    let pswd = "hunter2";
    let hashed = hash_password(pswd).unwrap();
    println!("Stored in DB: {}", hashed);
    
    let is_valid = verify_password(&hashed, "hunter2");
    println!("Is password valid? {}", is_valid);
}

Imagination Break: Imagine a hacker trying to crack Argon2 hashes. With MD5, they are a sprinter running on a smooth track. With Argon2, they are trying to run a marathon through waist-deep molasses while carrying a backpack full of rocks. It simply costs them too much energy (and money) to proceed. 🏃🧱


4. Creating an Auth Extractor for Protected Routes

Definition & Problem

The Problem: Using Identity in handlers works, but often we want to convert that identity immediately into a usable user struct (e.g., fetching the user profile from the DB) or return a specific 401 error if missing. Repeating this logic in every handler violates DRY (Don't Repeat Yourself).

The Solution: Implement the FromRequest trait for your User struct. This allows Actix Web to "extract" the user from the incoming request automatically. If the extraction fails (user not logged in), Actix handles the error before your handler even runs.

Implementation

We will create a struct AuthenticatedUser and implement FromRequest.

rust
use actix_web::{dev::Payload, FromRequest, HttpRequest, Error, error};
use std::future::{ready, Ready};
use actix_identity::Identity;

// This struct represents a user who has passed security checks
#[derive(Debug)]
pub struct AuthenticatedUser {
    pub id: String,
    pub username: String, // You might fetch this from DB in a real scenario
}

impl FromRequest for AuthenticatedUser {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
        // 1. Leverage the existing Identity extractor logic
        // We use `Identity::from_request` to verify the session exists
        let identity_future = Identity::from_request(req, pl);

        match identity_future.into_inner() {
            Ok(identity) => {
                // 2. If identity exists, get the ID
                match identity.id() {
                    Ok(id) => {
                        // In a real app, you might look up the user in the DB here.
                        // For now, we construct the struct directly.
                        ready(Ok(AuthenticatedUser {
                            id: id,
                            username: "UserFromDb".to_string(), 
                        }))
                    },
                    Err(_) => ready(Err(error::ErrorUnauthorized("Invalid Identity")))
                }
            },
            Err(_) => {
                // 3. If no identity, return 401 Unauthorized immediately
                ready(Err(error::ErrorUnauthorized("Please log in")))
            }
        }
    }
}

// Usage in Handler
// Look how clean the function signature is now!
async fn dashboard(user: AuthenticatedUser) -> impl Responder {
    format!("Welcome to the dashboard, user {}!", user.id)
}

This is the power of Rust and Actix. Your handler functions remain clean, purely focused on business logic, while the type system ensures security requirements are met before the function is entered.


Summary

  1. JWTs allow for stateless authentication.
  2. Argon2 is the heavy-lifting champion for password security.
  3. Middleware (Identity/Session) provides a transparent layer for managing auth state.
  4. Extractors (FromRequest) allow for declarative, type-safe route protection.

Security is a mindset, not a feature. Keep your dependencies updated and your secrets hidden.

References & Further Reading

Challenge

Challenge: Implement a Custom Actix Web Authentication Extractor

Your task is to implement a custom Actix Web extractor, AuthenticatedUser, by completing the FromRequest trait implementation.

This extractor will act as a guard for protected routes. Its logic must check if a user Identity is present in the incoming HttpRequest.

  1. If an Identity exists, the extractor should successfully resolve to an AuthenticatedUser instance containing the user's ID as a String.
  2. If no Identity is found, the extractor must fail by returning an ErrorUnauthorized error. This will prevent unauthenticated access to any handler that uses this extractor.

Expected result

The from_request method should be correctly implemented. The function body should use Identity::from_request(req).identity() to attempt to retrieve the user's session identity from the request's extensions.

The implementation must correctly handle the Option<String> returned:

  • On Some(user_id), it should create an AuthenticatedUser { id: user_id } instance and return ready(Ok(user)). A match or if let statement is suitable for this.
  • On None, it should return ready(Err(ErrorUnauthorized("Not authenticated"))) to signal that the request is unauthorized.
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.