Skip to main content

Authentication

Tutorials
    Authentication and Authorization with FastAPI: A Complete Guide | Better Stack Community
    Basic Authentication

    auth.py

    import secrets
    from fastapi import Depends, FastAPI, HTTPException, status
    from fastapi.security import HTTPBasic, HTTPBasicCredentials
    
    security = HTTPBasic()
    
    def authenticate_user(credentials: HTTPBasicCredentials = Depends(security)):
        # In a real application, you'd verify against a database
        correct_username = secrets.compare_digest(credentials.username, "admin")
        correct_password = secrets.compare_digest(credentials.password, "secret")
    
        if not (correct_username and correct_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid credentials",
                headers={"WWW-Authenticate": "Basic"},
            )
    
        return credentials.username

    main.py

    from fastapi import FastAPI, Depends
    from auth import authenticate_user
    
    app = FastAPI(title="Authentication Demo", version="1.0.0")
    
    @app.get("/")
    async def root():
        return {"message": "Welcome to FastAPI Authentication Demo"}
    
    @app.get("/protected")
    async def protected_route(current_user: str = Depends(authenticate_user)):
        return {"message": f"Hello {current_user}, this is a protected route!"}