HIGH man in the middleactixjwt tokens

Man In The Middle in Actix with Jwt Tokens

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

A Man In The Middle (MitM) scenario in Actix when JWT tokens are used typically arises when tokens are transmitted without adequate transport protection or when token validation is incomplete, enabling an attacker to intercept, read, or tamper with the authentication material. Even if JWTs are cryptographically signed, an attacker who can observe or modify traffic between client and server may attempt to capture tokens for reuse (token replay) or inject altered tokens if signature verification is misconfigured.

In Actix applications, risk increases when HTTPS is not enforced end-to-end, when tokens are passed in URLs or non-HTTP-only cookies, or when the server accepts unsigned or weakly signed tokens (e.g., 'none' algorithm). For example, if an Actix service exposes an HTTP endpoint that simply decodes the JWT payload without verifying the signature, an attacker positioned in the network path can replace the token with a forged one that impersonates any subject. Similarly, if the service relies on a forwarded header for the original URL without validating the Host, a proxy or load balancer misconfiguration may allow token leakage to unintended endpoints, effectively exposing authentication context to an observer.

Middleware inspection (black-box scanning) by middleBrick can surface these risks by checking whether the API enforces transport security, validates token signatures rigorously, and binds token usage to the intended channel and audience. The scanner’s checks include input validation and encryption to detect whether JWTs are accepted over non-TLS channels and whether tokens are handled in a way that facilitates replay or tampering.

Leveraging the OpenAPI/Swagger analysis capability, middleBrick cross-references spec definitions with runtime behavior to highlight mismatches—for instance, an endpoint declaring HTTPS but accepting requests over HTTP, or security schemes that do not enforce strict signature checks. This helps identify where MitM exposure intersects with JWT handling in Actix services.

Jwt Tokens-Specific Remediation in Actix — concrete code fixes

Remediation centers on enforcing strict transport security, validating JWT signatures, and avoiding unsafe practices. In Actix, use middleware to verify signatures and claims before routing to handlers, and always serve traffic over HTTPS.

Example secure configuration and validation in Actix using the jsonwebtoken crate:

use actix_web::{web, App, HttpServer, HttpResponse, middleware::Logger};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
    iss: String,
    aud: String,
}

async fn validate_jwt(auth_header: Option) -> Result, actix_web::Error> {
    let token = match auth_header {
        Some(h) => h.strip_prefix("Bearer ").ok_or_else(|| {
            actix_web::error::ErrorUnauthorized("Invalid authorization format")
        })?,
        None => return Err(actix_web::error::ErrorUnauthorized("Missing token")),
    };

    let validation = Validation::new(Algorithm::RS256);
    let token_data = decode::(
        token,
        &DecodingKey::from_rsa_pem(include_bytes!("/path/to/public_key.pem")).map_err(|_| {
            actix_web::error::ErrorUnauthorized("Invalid key")
        })?,
        &validation,
    ).map_err(|_| actix_web::error::ErrorUnauthorized("Invalid token"))?;

    // Enforce expected audience and issuer
    if token_data.claims.aud != "my-api-audience" || token_data.claims.iss != "trusted-issuer" {
        return Err(actix_web::error::ErrorUnauthorized("Token claims mismatch"));
    }

    Ok(token_data)
}

async fn protected_route(auth: web::Header>) -> HttpResponse {
    match validate_jwt(auth.map(|h| h.to_string())).await {
        Ok(_) => HttpResponse::Ok().body("Access granted"),
        Err(e) => HttpResponse::Unauthorized().body(e.to_string()),
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .route("/api/secure", web::get().to(protected_route))
    })
    .bind_rustls("0.0.0.0:8443", {
        let cert = std::fs::read("cert.pem").expect("cannot read cert.pem");
        let key = std::fs::read("key.pem").expect("cannot read key.pem");
        actix_web::web::OpenSSLListener::new(cert, key)
    })?
    .run()
    .await
}

Key practices:

  • Always use HTTPS (bind with TLS/Rustls) to prevent on-path interception.
  • Validate the signature with a strong algorithm (e.g., RS256) using a trusted public key.
  • Verify standard claims (iss, aud, exp, nbf) and bind token usage to the expected context.
  • Avoid the 'none' algorithm and do not accept unsigned tokens.
  • Store tokens securely on the client (prefer HttpOnly Secure cookies or secure storage) and avoid leaking them in URLs or logs.

middleBrick’s scans can verify that your Actix API enforces these practices by checking endpoint security configurations, encryption settings, and how JWTs are validated and transmitted.

Frequently Asked Questions

Does middleBrick test for JWT token leakage in URLs or logs during a scan?
Yes, middleBrick’s input validation and data exposure checks look for tokens being passed insecurely, such as in URLs or reflected in responses, and reports findings with remediation guidance.
Can the GitHub Action enforce JWT-related security gates in CI/CD for Actix services?
Yes, by adding the GitHub Action to your workflow and setting a risk score threshold, the build can fail if the API—including JWT handling—does not meet your security requirements before deployment.