HIGH man in the middleaxumjwt tokens

Man In The Middle in Axum with Jwt Tokens

Man In The Middle in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability

In an Axum application that relies on JWT tokens for authentication, a Man In The Middle (MitM) attack occurs when an adversary can intercept or tamper with HTTP traffic between the client and the server. Because JWTs are often transmitted in the Authorization header as a bearer token, an attacker on the same network (e.g., unencrypted Wi‑Fi, compromised router, or malicious proxy) can capture the token if the connection is not protected by TLS. Once captured, the token can be reused to impersonate the user or escalate privileges, commonly violating authentication and authorization controls such as BOLA/IDOR and BFLA/Privilege Escalation that are included in the 12 parallel security checks.

Even when JWTs are cryptographically signed, signing alone does not prevent interception; without transport-layer encryption, an attacker can perform session hijacking by replaying the token. Insecure defaults, such as allowing HTTP alongside HTTPS or failing to set the Secure and HttpOnly flags on cookies (if used), amplify the risk. The unscoped nature of many JWT implementations in APIs also means that stolen tokens can be used across multiple endpoints, increasing the impact of token leakage. This exposes issues around Data Exposure and Encryption, as tokens may carry claims that should remain confidential and may be decoded by an attacker to reveal PII or role information.

middleBrick scans for these risks by checking whether unauthenticated endpoints transmit JWTs over non-encrypted channels and by flagging missing transport protections as part of its Encryption and Data Exposure checks. Because the scanner runs without agents or credentials, it can identify whether your Axum API is vulnerable to token interception in real-world network conditions, providing findings mapped to frameworks such as OWASP API Top 10 and GDPR.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

To mitigate MitM risks with JWT tokens in Axum, enforce strict HTTPS, validate token handling in middleware, and ensure tokens are not transmitted over insecure channels. Below are concrete, working examples that demonstrate secure practices.

1. Force HTTPS and reject insecure connections in your Axum service.

use axum::middleware::Next;
use axum::response::Response;
use axum::http::request::Parts;
use std::convert::Infallible;

async fn https_redirect_middleware(
    req: Parts,
    next: Next,
) -> Result {
    if req.headers.get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .map(|s| s != "https")
        .unwrap_or(true)
    {
        // Return 400 or redirect to HTTPS as appropriate for your deployment
        return Ok(Response::builder()
            .status(400)
            .body("HTTPS required".into())
            .unwrap());
    }
    next.run(req).await
}

2. Validate JWTs using a verified library and ensure the token is not logged or exposed in error messages.

use axum::async_trait;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
    pub sub: String,
    pub roles: Vec,
    pub exp: usize,
}

pub struct JwtValidator {
    decoding_key: DecodingKey,
    validation: Validation,
}

impl JwtValidator {
    pub fn new(secret: &[u8]) -> Self {
        Self {
            decoding_key: DecodingKey::from_secret(secret),
            validation: Validation::new(Algorithm::HS256),
        }
    }

    pub fn validate(&self, token: &str) -> Result, jsonwebtoken::errors::Error> {
        decode::(token, &self.decoding_key, &self.validation)
    }
}

// Example usage in an Axum extractor
use axum::extract::Request;
use std::sync::Arc;

pub async fn validate_jwt_from_request(
    request: Request,
    validator: Arc,
) -> Result {
    let auth_header = request.headers()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim_start_matches("Bearer "))
        .ok_or((StatusCode::UNAUTHORIZED, "Missing bearer token".into()))?;

    let token_data = validator.validate(auth_header)
        .map_err(|e| (StatusCode::UNAUTHORIZED, format!("Invalid token: {}", e)))?;
    Ok(token_data.claims)
}

3. Configure secure cookie attributes if you store JWTs in cookies, and avoid including sensitive data in the JWT payload.

use axum::response::SetCookie;
use axum::http::Cookie;

let cookie = Cookie::build(("auth_token", token))
    .secure(true)
    .http_only(true)
    .same_site(axum::http::CookieSameSite::Strict)
    .path("/")
    .finish();
axum::response::Response::builder()
    .header(axum::http::header::SET_COOKIE, cookie.to_string())
    .body(axum::body::boxed(axum::body::Body::empty()))
    .unwrap();

4. Apply role-based checks and BOLA/IDOR protections after token validation to ensure that users can only access resources they are authorized to use.

use axum::http::StatusCode;

fn ensure_own_resource(user_id: &str, resource_id: &str) -> Result<(), (StatusCode, String)> {
    if user_id != resource_id {
        return Err((StatusCode::FORBIDDEN, "Access denied".into()));
    }
    Ok(())
}

By integrating these patterns, an Axum service reduces the attack surface for MitM against JWT tokens and aligns with the remediation guidance provided in middleBrick findings, which include prioritized steps and references to compliance mappings.

Frequently Asked Questions

Does middleBrick test whether JWT tokens are transmitted over HTTPS in an Axum API?
Yes. middleBrick checks whether unauthenticated endpoints send JWT tokens over non-encrypted channels and flags missing HTTPS as part of its Encryption and Data Exposure checks.
Can middleBrick detect JWT token leakage risks such as missing Secure or HttpOnly flags in Axum?
middleBrick identifies insecure transport and token exposure risks. It does not inspect cookie flags set by application code directly, but findings include remediation guidance to use Secure, HttpOnly, and SameSite attributes for any cookies storing tokens.