HIGH missing tlsfastapibasic auth

Missing Tls in Fastapi with Basic Auth

Missing Tls in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Using HTTP Basic Authentication in a FastAPI application without Transport Layer Security (TLS) exposes credentials in transit. Basic Auth encodes a username and password with Base64, which is easily reversible. Without TLS, the encoded string can be intercepted and decoded by an attacker on the network path, leading to immediate credential compromise. middleBrick scans detect this risk by observing unauthenticated endpoints and flagging the absence of enforced HTTPS as a transport-layer finding.

In a black-box scan, middleBrick checks whether requests to the API are served over plain HTTP and whether sensitive authentication mechanisms are exposed without encryption. When Basic Auth is present and TLS is missing, the tool highlights the lack of encryption as a high-severity transport issue. This is especially critical because the credentials are included in every request header, and interception requires minimal attacker effort on shared or untrusted networks.

Even if the API specification documents HTTPS as expected, runtime checks may reveal that the server responds on HTTP. middleBrick’s OpenAPI/Swagger analysis resolves all $ref references and cross-references spec-defined schemes with runtime behavior. If the spec indicates HTTPS but the service replies on HTTP, this inconsistency is surfaced as a deviation, emphasizing the gap between intended and actual security posture.

Attack patterns such as credential sniffing on local networks, malicious Wi‑Fi access points, or compromised network infrastructure make this combination particularly dangerous. Because Basic Auth sends credentials with every request, the window of exposure is persistent across the session. Without TLS, there is no encryption or integrity protection, making the channel vulnerable to both passive eavesdropping and active tampering.

middleBrick’s findings include prioritized guidance to enforce TLS and to avoid sending credentials in the clear. The scanner does not fix the issue but provides remediation steps, such as obtaining and configuring a valid certificate and ensuring the server redirects all HTTP traffic to HTTPS.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

To secure FastAPI with HTTP Basic Authentication, you must enforce HTTPS and avoid sending credentials over unencrypted channels. Below are concrete code examples that implement Basic Auth correctly with TLS enforcement.

Enable HTTPS in FastAPI

Configure your ASGI server (for example, Uvicorn) with an SSL certificate. Use standard parameters to start the server with TLS:

uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile=key.pem --ssl-certfile=cert.pem

FastAPI Basic Auth implementation with HTTPS redirection

This example shows a FastAPI application that uses HTTP Basic Authentication and ensures all traffic is served over HTTPS by redirecting HTTP to HTTPS at a load balancer or proxy. The authentication logic remains simple and focused on credential verification.

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import uvicorn

app = FastAPI()
security = HTTPBasic()

def verify_credentials(credentials: HTTPBasicCredentials):
    # Replace with secure credential verification, e.g., hashed check
    correct_username = "admin"
    correct_password = "securepassword"
    if credentials.username != correct_username or credentials.password != correct_password:
        return False
    return True

@app.get("/secure-endpoint")
def secure_endpoint(credentials: HTTPBasicCredentials = Depends(security)):
    if not verify_credentials(credentials):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    return {"message": "Authenticated"}

if __name__ == "__main__":
    # Run with TLS in production; this command is for local testing only
    uvicorn.run(app, host="0.0.0.0", port=8000)

Infrastructure-level enforcement

While FastAPI can serve HTTPS directly, it is common to enforce TLS at a reverse proxy or load balancer. Ensure your infrastructure redirects all HTTP requests to HTTPS and terminates TLS before reaching the application. This prevents accidental cleartext exposure and aligns with transport-layer security best practices.

Credential storage and transmission

Never store credentials in plaintext. Use secure vaults or environment variables for secrets. For Basic Auth, consider replacing it with token-based authentication (for example, OAuth2 with bearer tokens) where feasible, reducing the risk of credential replay. middleBrick findings often recommend stronger alternatives when Basic Auth is used without additional protections.

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

Why does middleBrick flag missing TLS even when Basic Auth is implemented in FastAPI?
middleBrick flags missing TLS because Basic Auth encodes credentials in reversible Base64 and relies entirely on transport encryption. Without HTTPS, credentials are exposed in transit regardless of how securely they are stored or verified in the application.
Can middleBrick detect unauthenticated endpoints using Basic Auth that still lack TLS?
Yes, middleBrick tests the unauthenticated attack surface and identifies endpoints that accept credentials without TLS. It cross-references spec definitions with runtime behavior to highlight inconsistencies and transport-layer risks.