Phishing Api Keys in Fastapi with Basic Auth
Phishing API Keys in FastAPI with Basic Auth — how this specific combination creates or exposes the vulnerability
When Basic Authentication is used in a FastAPI application without additional protections, API keys or long-lived credentials can be phished through both social engineering and implementation weaknesses. Basic Auth sends credentials with every request as an Authorization header of the form Authorization: Basic base64(username:password). Because the credentials are only base64-encoded and not encrypted, they are easily decoded if intercepted or if a user is tricked into providing them to a malicious actor or site.
In a phishing scenario targeting FastAPI services using Basic Auth, attackers may craft fake login pages or API documentation that prompt users to paste credentials. Because Basic Auth embeds the credential directly in the header, pasting into a malicious client or script can expose the token or password directly. Additionally, if the FastAPI route handling authentication does not strictly validate the Authorization header and does not enforce HTTPS, credentials can be exposed in transit or via logs. Attackers may also probe endpoints that expose API keys via error messages or open endpoints, combining information disclosure with weak authentication to escalate to unauthorized access.
When combined with insufficient input validation or missing rate limiting, phishing attempts can be automated against the FastAPI service. For example, attackers may use credential stuffing or token harvesting scripts that submit guessed or phished credentials to authentication routes. If the application does not properly separate authentication concerns and does not require additional verification factors beyond Basic Auth, the API key or password becomes the effective bearer token, enabling misuse if leaked.
The middleBrick scanner includes checks for Authentication weaknesses and Input Validation, which can surface exposed authentication patterns and missing protections in FastAPI services. By analyzing the OpenAPI specification and runtime behavior, the scanner can identify routes accepting Basic Auth without additional safeguards such as strict transport enforcement or multi-factor challenges. These findings highlight where phishing risks are elevated and provide remediation guidance to reduce the attack surface.
Complementary capabilities such as the middleBrick LLM/AI Security checks further help detect whether authentication endpoints or error responses inadvertently expose API keys or system prompts that could aid phishing. System prompt leakage detection and active prompt injection testing ensure that AI-integrated FastAPI endpoints do not reveal sensitive instructions or credentials. Together, these checks support a defense-in-depth approach, helping teams detect weak authentication configurations before attackers exploit them.
Basic Auth-Specific Remediation in FastAPI — concrete code fixes
To reduce phishing risk and strengthen Basic Auth in FastAPI, enforce HTTPS, avoid embedding secrets in headers without additional protection, and apply strict validation. Always require TLS in production so credentials are not transmitted in cleartext. Prefer token-based authentication where feasible, but if Basic Auth is required, combine it with additional checks such as HSTS, strict header validation, and secure credential storage.
Example secure FastAPI implementation with Basic Auth:
from fastapi import FastAPI, Depends, HTTPException, status, Security
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets
from typing import Optional
app = FastAPI()
security = HTTPBasic()
# In production, store credentials securely (e.g., environment variables or a secrets manager)
VALID_USERS = {
"admin": "$2b$12$EXAMPLEHASHFORADMIN" # store a strong bcrypt hash
}
def verify_credentials(credentials: HTTPBasicCredentials):
username = credentials.username
provided_password = credentials.password
if username not in VALID_USERS:
return False
# Use a proper password hashing library such as passlib with bcrypt
# Placeholder for hashed comparison; replace with real hashed check
stored_hash = VALID_USERS[username]
# Example: use passlib to verify; here we simulate a check
return secrets.compare_digest(stored_hash, "$2b$12$EXAMPLEHASHFORADMIN")
@app.get("/secure-endpoint")
async def secure_route(credentials: HTTPBasicCredentials = Security(security)):
if not verify_credentials(credentials):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"}
)
return {"message": "Authenticated", "user": credentials.username}
@app.get("/open-info")
def open_info():
# Avoid exposing API keys or secrets in public endpoints
return {"info": "Public endpoint, no authentication required"}
Key remediation practices:
- Enforce HTTPS using middleware or startup events to redirect HTTP to HTTPS and set HSTS headers.
- Never log
Authorizationheaders or credentials; sanitize logs to prevent credential leakage. - Validate and sanitize all inputs related to authentication to prevent injection or header manipulation.
- Apply rate limiting to authentication endpoints to mitigate credential stuffing and automated phishing attempts.
- Use strong password hashing (e.g., bcrypt) and rotate credentials regularly; avoid storing plaintext or weakly encoded secrets.
- Consider adding multi-factor authentication or step-up challenges for sensitive operations, reducing reliance on Basic Auth alone.
Using the middleBrick CLI (middlebrick scan <url>) or GitHub Action helps verify that these protections are in place by scanning the FastAPI service and flagging missing HTTPS, weak authentication patterns, and input validation issues. The dashboard can track changes over time, and the Pro plan’s continuous monitoring can alert teams if risky configurations reappear after updates.