axum_jwt_ware 0.1.2

Axum Authentication Library
Documentation

axum_jwt_ware Integration Guide

Simple Axum + JWT authentication middleware with Login implemented.

Goal

Installation

cargo add axum_jwt_ware

Usage example

There is one standard middleware for verifying a user via JWT -- the verify_user middleware. Its signature looks like this:

pub async fn verify_user<B>(
    mut req: Request<B>,
    key: &DecodingKey,
    validation: Validation,
    next: Next<B>,
) -> Result<Response, AuthError>

So, you can pass it to the route layer as shown below:

use crate::{
    verify_user,
    Claims, CurrentUser, UserData, DecodingKey, EncodingKey, Validation, Header
};
let app = Router::new()
    .route(
        "/hello",
        get(hello_handler)
        .layer(middleware::from_fn(move |req, next| {
            let key = DecodingKey::from_secret("secret_from_your_env".as_ref());
            let validation = Validation::default();
            async move {
                verify_user(req, &key, validation, next).await
            }
        })),
    )

Login

use axum_jwt_ware::{CurrentUser, UserData};

#[derive(Clone, Copy)]
pub struct MyUserData;

impl UserData for MyUserData {
    fn get_user_by_email(&self, _email: &str) -> Option<CurrentUser> {
        // Implement the logic to fetch user by email from your database
    }   
}

let app = Router::new()
.route("/login", post(move | body: Json<axum_jwt_ware::RequestBody>| {
    let user_data = MyUserData;
    let jwt_secret = "secret_from_env";
    let expiry_timestamp = Utc::now() + Duration::hours(48);

    login(body, user_data.clone(), jwt_secret, expiry_timestamp ) // login returns {username, token}
}));
use axum_jwt_ware::{CurrentUser, UserData, Algorithm auth_token_encode};
let key = EncodingKey::from_rsa_pem(include_bytes!("../jwt.key")).unwrap();
let mut header = Header::new(Algorithm::RS256);
let expiry_timestamp = Utc::now() + Duration::hours(48);

let claims = Claims {
    sub: user.id,
    username: user.username.clone(),
    exp: expiry_timestamp,
};
let token = auth_token_encode(claims, header, &key).await;

Features

  • [] Refresh Token

  • Login

    • You can imlement your own login
    • Use the provided login
  • Authentication Middleware

  • [] Test

  • Create an issue
  • Fork the repo
  • Create a PR that fixes the issue