watem

Crates.iowatem
lib.rswatem
version0.1.0
created_at2025-12-30 10:54:04.36147+00
updated_at2025-12-30 10:54:04.36147+00
descriptionSimple Bearer Token Extractor Middleware
homepage
repositoryhttps://github.com/Axoneo/watem.git
max_upload_size
id2012467
size38,059
Softplus+ (softplus10)

documentation

README

watem

Simple Bearer Token Extractor Middleware for Rust.

This library provides a convenient way to validate JWT tokens and extract claims, with built-in support for the Axum web framework.

Features

  • Framework-agnostic: Core validation logic can be used anywhere.
  • Axum Support: Ready-to-use Claims extractor for Axum handlers (via axum feature).
  • Flexible: Works with any serializable/deserializable Claims structure.

Installation

Add this to your Cargo.toml:

[dependencies]
watem = { version = "0.1.0", features = ["axum"] }

Usage

Axum Integration

To use with Axum, enable the axum feature and add the TokenValidator to your application state. Then, simply use Claims<T> in your handler arguments.

use watem::{TokenValidator, axum_support::Claims};
use axum::{routing::get, Router, Json};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct MyClaims {
    sub: String,
    exp: usize,
}

// The extractor will automatically:
// 1. Get the Authorization header
// 2. Check for "Bearer " scheme
// 3. Validate the JWT signature and expiration
// 4. Deserialize the claims into MyClaims
async fn protected_handler(Claims(claims): Claims<MyClaims>) -> Json<MyClaims> {
    println!("Authenticated user: {}", claims.sub);
    Json(claims)
}

#[tokio::main]
async fn main() {
    // 1. Create a validator (e.g., using HS256)
    let secret = b"your-secret-key";
    let validator = TokenValidator::new_hs256(secret);
    
    // 2. Wrap in Arc for shared state
    let state = Arc::new(validator);

    // 3. Add state to your router
    let app = Router::new()
        .route("/protected", get(protected_handler))
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("Listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

Basic Usage (No Framework)

You can also use the validator directly without any web framework.

use watem::{TokenValidator, JwtError};
use serde::Deserialize;

#[derive(Deserialize)]
struct MyClaims {
    sub: String,
    exp: usize,
}

fn main() -> Result<(), JwtError> {
    let secret = b"secret";
    let validator = TokenValidator::new_hs256(secret);
    
    let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."; // Your JWT token
    
    // Validate and extract claims
    let claims: MyClaims = validator.validate(token)?;
    
    println!("Subject: {}", claims.sub);
    Ok(())
}

License

Unlicense

Commit count: 0

cargo fmt