HIGH missing tlsaxumjwt tokens

Missing Tls in Axum with Jwt Tokens

Missing Tls in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Transport Layer Security (TLS) ensures confidentiality and integrity for data in transit. When an Axum API that issues or validates JWT tokens does not enforce TLS, tokens can be intercepted or modified between client and server. This is especially critical because JWT tokens often carry identity and authorization claims; exposing them undermines the entire access control model.

In practice, an Axum service might accept incoming HTTP connections on port 80 or bind to 0.0.0.0 without redirecting to HTTPS. An attacker on the same network can capture unencrypted requests and responses, including Authorization headers containing bearer tokens. Even if tokens are cryptographically signed, interception enables token replay and session hijacking (broken authentication and session management, OWASP API Top 10). MiddleBrick scans this attack surface during black-box testing and flags missing TLS as a high-severity finding because it exposes JWT material regardless of the signing algorithm used.

Additionally, JWT tokens passed in URLs or query parameters are more likely to leak in logs and browser history when TLS is absent. MiddleBrick’s Data Exposure check detects cleartext transmission of sensitive payloads and maps the finding to frameworks such as OWASP API Top 10 and SOC2. The scanner does not assume internal mitigations; it validates what an external observer can see, which commonly reveals missing TLS in Axum configurations that lack proper redirection or certificate binding.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

To remediate missing TLS for JWT tokens in Axum, enforce HTTPS for all routes and ensure tokens are transmitted only over encrypted channels. Below are concrete, working examples that integrate TLS redirection and secure JWT handling in Rust using Axum, Tower, and jsonwebtoken.

1. Enforce HTTPS and redirect HTTP to HTTPS

Run two separate services: one for redirecting cleartext requests, and one serving your application over TLS.

use axum::{Router, routing::get};
use std::net::SocketAddr;
use tower_http::services::ServeDir;

// HTTP handler that redirects to HTTPS
async fn redirect_to_https() -> &'static str {
    "Redirecting to HTTPS"
}

#[tokio::main]
async fn main() {
    let https_addr = SocketAddr::from(([0, 0, 0, 0], 8443));
    let http_addr = SocketAddr::from(([0, 0, 0, 0], 8080));

    let app = Router::new()
        .route("/health", get(|| async { "ok" }));

    // HTTPS server with TLS certificates
    let https = axum::Server::bind(&https_addr)
        .https()
        .cert_path("cert.pem")
        .key_path("key.pem")
        .serve(app.into_make_service());

    // HTTP redirect server
    let http_redirect = axum::Server::bind(&http_addr)
        .serve(axum::Router::new()
            .route("/(.*)?", get(redirect_to_https))
            .into_make_service());

    tokio::join!(https, http_redirect);
}

2. Secure JWT issuance and validation over HTTPS

Ensure tokens are issued only after successful authentication and are validated on each request. Use middleware to check Authorization headers and reject requests not using HTTPS.

use axum::{http::HeaderValue, extract::Request, middleware::Next, response::Response};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData};

async fn require_https(req: Request, next: Next) -> Response {
    if req.uri().scheme().map(|s| s != &"https").unwrap_or(true) {
        return Response::builder()
            .status(403)
            .body("HTTPS required".into())
            .unwrap();
    }
    next.run(req).await
}

async fn validate_jwt(req: Request, next: Next) -> Response {
    let auth_header = req.headers().get("authorization");
    let token = match auth_header.and_then(|v| v.to_str().ok()) {
        Some(v) if v.starts_with("Bearer ") => &v[7..],
        _ => return Response::builder().status(401).body("Missing token".into()).unwrap(),
    };

    let validation = Validation::new(Algorithm::HS256);
    let token_data: TokenData = match decode::(
        token,
        &DecodingKey::from_secret("secret".as_ref()),
        &validation,
    ) {
        Ok(t) => t,
        Err(_) => return Response::builder().status(401).body("Invalid token".into()).unwrap(),
    };

    // Attach claims for downstream handlers
    let extensions = req.extensions();
    extensions.insert(token_data.claims);
    next.run(req).await
}

// Example handler that requires HTTPS and valid JWT
async fn protected(claims: Claims) -> &'static str {
    "Access granted"
}

3. Serve static assets and API routes with TLS only

Configure your reverse proxy or load balancer to terminate TLS and forward only HTTPS traffic to Axum. In Axum, reject non-HTTPS requests at the middleware layer as shown above. This ensures JWT tokens are never exposed in cleartext, mitigating interception and replay risks identified by MiddleBrick’s scanning checks.

Finally, rotate signing keys regularly and avoid embedding secrets in source code. MiddleBrick’s Secret Scanning checks can detect accidental exposure of JWT secrets in repositories; use environment variables or secret managers and reference them securely in your Axum configuration.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

What does MiddleBrick report when TLS is missing for JWT endpoints?
MiddleBrick reports a high-severity finding under Data Exposure and Transport Security checks, noting that JWT tokens are transmitted in cleartext and mapping the issue to relevant compliance controls.
Can MiddleBrick detect missing TLS automatically?
Yes. By scanning unauthenticated attack surfaces, MiddleBrick detects whether endpoints serving JWT tokens lack HTTPS and flags the exposure during the scan.