Token Leakage in Axum with Jwt Tokens
Token Leakage in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Token leakage in an Axum application using JWT tokens occurs when a JSON Web Token is unintentionally exposed in logs, error messages, URLs, or cross-service boundaries. Because Axum is a Rust web framework that does not enforce a global authentication policy, developers must explicitly integrate JWT validation and control how tokens flow through handlers, middleware, and responses. If JWT handling is implemented without care, tokens can be written to logs, echoed in HTTP responses, or passed to downstream services where they are not required, expanding the unauthenticated attack surface that middleBrick scans for under its Authentication and Data Exposure checks.
In Axum, a common pattern is to extract the token from an Authorization header, validate it, and attach claims to a request extension for downstream handlers. If the token value is included in structured logging statements—such as logging the full header map or the claims struct directly—middleBrick’s Data Exposure checks may flag the endpoint because tokens can appear in log aggregation systems. For example, writing info!("token: {:?} {token}) or including the token in an error response body can expose bearer credentials to anyone who can view logs or intercept error payloads. A related risk arises when developers propagate tokens to upstream or downstream HTTP calls without stripping them, effectively leaking the same JWT across service boundaries and creating potential BOLA/IDOR conditions if the token is tied to a specific subject or scope.
Another leakage vector specific to JWT usage in Axum is improper error handling during validation. When a token fails verification, an Axum handler might return the raw token string in a JSON error field, such as { "error": "invalid_token", "token": "eyJhbGci..." }. This practice directly contributes to Data Exposure findings because the token is now persisted or transmitted beyond the secure channel. Similarly, if an OpenAPI spec generated for an Axum service includes security schemes that inadvertently expose bearer tokens in query parameters (e.g., via a security requirement that incorrectly allows the token in headers and query without constraining the parameter location), middleBrick’s OpenAPI/Swagger analysis can detect mismatches between declared and expected token usage, highlighting paths where tokens may be cached or logged unintentionally.
Because middleBrick tests the unauthenticated attack surface and runs 12 security checks in parallel, endpoints in Axum that expose JWT tokens through error responses, logs, or cross-service headers may trigger Authentication misconfiguration and Data Exposure findings. The scanner does not make assumptions about internal architecture; it observes runtime behavior and spec declarations to correlate token handling patterns with concrete risks. For teams using the CLI tool, running middlebrick scan <url> can surface these leakage paths without requiring credentials or agents, making it straightforward to validate that JWT tokens remain confined to secure, intended channels.
Jwt Tokens-Specific Remediation in Axum — concrete code fixes
Remediation for token leakage in Axum centers on disciplined handling of JWT tokens at extraction, validation, logging, and error reporting. Use typed extractors to enforce that tokens are read only from secure headers and never from query parameters. Ensure validation failures return generic error messages that do not include the token, and structure logs to redact or omit bearer values. Below are concrete patterns that align with Axum middleware design and reduce the likelihood of leakage flagged by middleBrick’s checks.
First, define a JWT validation extractor that returns a typed claims struct only when verification succeeds, and ensure no token string is propagated into logs or responses:
use axum::{async_trait, extract::{FromRequest, RequestParts}};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::Deserialize;
use std::convert::Infallable;
#[derive(Debug, Deserialize)]
struct Claims {
sub: String,
exp: usize,
}
struct Jwt(String);
#[async_trait]
impl FromRequest<S> for Jwt
where
S: Send + Sync,
{
type Rejection = (axum::http::StatusCode, String);
async fn from_request(req: &mut RequestParts<S>) -> Result<Self, Self::Rejection> {
let headers = req.headers();
let auth = headers.get("authorization")
.and_then(|v| v.to_str().ok())
.filter(|s| s.starts_with("Bearer "))
.map(|s| s.trim_start_matches("Bearer ").to_string())
.ok_or((axum::http::StatusCode::BAD_REQUEST, "Missing or malformed authorization header".to_string()))?;
// Validate without logging the raw token
let _claims = decode::
This extractor ensures the token is read from the Authorization header only, and it avoids echoing the token in error responses. The error messages are generic and do not include the JWT string, which helps prevent Data Exposure findings related to token leakage in responses.
Second, when logging authenticated requests, redact the token value. For example, log user identifiers or request IDs instead of the full token:
use tracing::info;
async fn handler(
Jwt(_token): Jwt,
claims: axum::extract::Extension<Claims>,
) -> String {
// Safe: do not log the token itself
info!(user_id = %claims.sub, "handled authenticated request");
"ok".to_string()
}
Third, avoid propagating JWTs to downstream HTTP clients or services unless explicitly required. If you must forward requests, remove the Authorization header to prevent unintended leakage:
use reqwest::Client;
async fn forward_request(original_token: String) -> reqwest::Result {
let client = Client::new();
// Intentionally omit Authorization header to avoid leaking the token
client.get("https://upstream.example.com/resource")
.send()
.await
}
By combining a secure extractor, redacted logging, and strict header control when calling downstream services, you reduce the observable attack surface that middleBrick scans for under its Authentication, BOLA/IDOR, and Data Exposure checks. These practices align with the remediation guidance provided in the scanner output and help ensure JWT tokens remain confined to their intended security boundary.