Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Authentication Basics📚 API Keys📚 Basic Auth📚 JWT Tokens📚 OAuth2📚 Scopes📚 Securing Endpoints📚 Token Refresh📚 Role-Based Access
Fastapi/Authentication/Basic Auth

HTTP Basic Authentication

Basic authentication sends username and password with each request encoded in Base64. Simple but requires HTTPS for security.

How Basic Auth Works

Credentials are encoded and sent in the Authorization header:

from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
import secrets

app = FastAPI()
security = HTTPBasic()

@app.get("/basic")
async def basic_auth(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = secrets.compare_digest(credentials.username, "user")
    correct_password = secrets.compare_digest(credentials.password, "pass")
    
    if not (correct_username and correct_password):
        raise HTTPException(status_code=401, detail="Invalid credentials")
    
    return {"message": f"Hello {credentials.username}"}

Validating Credentials

from fastapi.security import HTTPBasic, HTTPBasicCredentials

security = HTTPBasic()

async def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    # Check against database
    user = authenticate_user(credentials.username, credentials.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return user

@app.get("/protected")
async def protected(user: dict = Depends(get_current_user)):
    return {"user": user}

Hashing Passwords

from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str):
    return pwd_context.hash(password)

def verify_password(plain, hashed):
    return pwd_context.verify(plain, hashed)

Common Patterns and Best Practices

  • ✅ Always use HTTPS with basic auth
  • ✅ Hash passwords with bcrypt or similar
  • ✅ Implement account lockout after failed attempts
  • ✅ Use secure password requirements
  • ✅ Never log passwords
  • ✅ Implement password reset securely
  • ✅ Use rate limiting to prevent brute force
  • ✅ Consider two-factor authentication

Real-World Usage

Basic auth is suitable for:

  • Simple internal tools
  • Development/testing
  • Legacy system integration
  • Basic microservice communication

Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn