Vulnerable Components in Fastapi with Basic Auth
Vulnerable Components in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability
Basic authentication in FastAPI is commonly implemented by sending credentials in the Authorization header as Basic base64(username:password). While the transport format itself is straightforward, this combination introduces several specific risks when used without mandatory protections. Because Base64 is reversible and not encryption, credentials are easily decoded if intercepted, making transport security essential. Without HTTPS, credentials are exposed in transit, enabling credential theft and session hijacking.
When integrated with FastAPI’s dependency injection system, developers often create dependencies that call HTTPBearer() or manually parse the header but fail to enforce HTTPS globally, validate credentials on each request, or protect against timing attacks. This can lead to authentication bypass via weak or missing validation, insecure storage of credentials in code or environment variables, and exposure of endpoints that should require authentication. In a black-box scan, middleBrick checks whether authentication is enforced over TLS and whether credentials are transmitted or stored securely, flagging endpoints that accept Basic Auth without HTTPS as high risk.
Another vulnerability pattern arises when Basic Auth is used for unauthenticated or improperly constrained endpoints. For example, if a dependency is applied at the router level but overridden at the operation level without equivalent protection, some routes may be exposed. Additionally, logging or error messages may inadvertently disclose authorization headers, leading to information exposure. middleBrick’s authentication checks look for these gaps, including whether the server responds with different status codes or timing behavior for valid versus invalid credentials, which may indicate authorization logic flaws (BOLA/IDOR) or weak access controls.
Basic Auth also interacts poorly with caching layers and reverse proxies that may log or store headers. If credentials appear in logs, monitoring systems, or browser history, the risk of exposure increases. In API specifications described by OpenAPI 2.0 or 3.0, failing to mark security requirements consistently or using securitySchemes without applying them to all relevant operations can create mismatches between documented and actual enforcement. middleBrick cross-references the spec definitions with runtime behavior to detect such inconsistencies, highlighting endpoints that appear documented as protected but are not enforced at runtime.
Finally, because Basic Auth does not inherently include mechanisms for token rotation, revocation, or scopes, it can encourage long-lived credentials with broad permissions. This elevates the impact of compromised credentials and can facilitate privilege escalation when used in endpoints that also expose user identifiers or allow indirect object references. The combination of Basic Auth with insufficient authorization checks increases the likelihood of BOLA/IDOR and privilege escalation (BFLA), making it important to validate ownership and permissions on a per-request basis.
Basic Auth-Specific Remediation in Fastapi — concrete code fixes
To secure Basic Auth in FastAPI, enforce HTTPS across the application and avoid sending credentials in clear text. Always use Security Scopes and require explicit authentication for protected routes. Below are concrete code examples that implement secure Basic Auth with proper validation and HTTPS enforcement.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.responses import PlainTextResponse
import secrets
import ssl
app = FastAPI()
security = HTTPBasic()
# In production, store credentials securely, for example using environment variables
# and a secure secret manager. Avoid hardcoding credentials.
VALID_USERS = {
"admin": secrets.token_hex(16) # simulate a hashed or rotated credential
}
def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
correct_password = VALID_USERS.get(credentials.username)
if not correct_password or not secrets.compare_digest(correct_password, credentials.password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/secure-data", dependencies=[Depends(verify_credentials)])
async def secure_data():
return {"message": "Authenticated access granted"}
# Optional: Enforce HTTPS in production by requiring secure cookies and strict transport
# This should be complemented by infrastructure-level TLS termination.
@app.get("/public-info")
async def public_info():
return PlainTextResponse("Public endpoint, no auth required")
For broader protection, apply the dependency at the router level and ensure all operations inherit the requirement unless explicitly overridden with equivalent security. Use middleware or startup events to verify that HTTPS is enforced in production environments.
from fastapi import FastAPI, Request
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
app = FastAPI()
app.add_middleware(HTTPSRedirectMiddleware)
Document the security scheme clearly in your OpenAPI specification so that tools like middleBrick can map declared protections to runtime behavior. Use security fields in path objects and define a securitySchemes entry for HTTP Basic, ensuring that every sensitive route references it. Regularly rotate credentials and audit logs for unauthorized access attempts to reduce exposure.