python

Ready to Make Your FastAPI App Impossibly Secure with 2FA?

Guard Your FastAPI Castle With Some 2FA Magic

Ready to Make Your FastAPI App Impossibly Secure with 2FA?

Implementing two-factor authentication, or 2FA, in FastAPI is an essential trick to toughen up your web app’s security. It’s about throwing in an extra obstacle for the bad guys. They’d need to know your password and have something else, like a one-time code from an app on your phone. So even if someone cracks your password, they’d still need your phone to get in.

Let’s dive into how to rig up 2FA in FastAPI. We’ll need a few tools and libraries for the job. The first task is to set up your FastAPI environment with the basics and install the necessary libraries, like pyotp for one-time passwords and qrcode for generating QR codes.

Grab your favorite terminal and punch in:

pip install fastapi uvicorn pyotp qrcode

Once that’s done, the next step is all about generating a secret key. This key is going to be the ingredient that makes your one-time passwords. With pyotp, whipping up a random secret key is a breeze:

import pyotp

secret_key = pyotp.random_base32()

Now, we need a place to store user stuff, including our secret key. Using Pydantic to create a user model looks something like this:

from pydantic import BaseModel

class User(BaseModel):
    username: str
    password: str
    secret_key: str
    otp_enabled: bool = False

With the secret key in hand, it’s QR code time. The QR code is what users will scan with their authenticator apps to set up their one-time passwords. It packages all the necessary info.

import qrcode

totp = pyotp.TOTP(secret_key)
uri = totp.provisioning_uri(name="[email protected]", issuer_name="Your App")
qrcode.make(uri).save("qr_code.png")

Moving on to user signup and getting 2FA running, here’s the idea. When folks sign up, generate a secret key, cook up a QR code, and stash the secret key in the user’s profile:

from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import FileResponse

app = FastAPI()

@app.post("/signup")
async def signup(user: User):
    # Generate secret key and QR code
    secret_key = pyotp.random_base32()
    totp = pyotp.TOTP(secret_key)
    uri = totp.provisioning_uri(name=user.username, issuer_name="Your App")
    qrcode.make(uri).save("qr_code.png")
    
    # Store the secret key in the user's profile
    user.secret_key = secret_key
    user.otp_enabled = True
    
    return {"message": "User created successfully", "qr_code": "qr_code.png"}

@app.get("/qr_code")
async def get_qr_code():
    return FileResponse("qr_code.png", media_type="image/png")

Next, the user needs an authenticator app, like Google Authenticator or Microsoft Authenticator, to scan the QR code. Once they have done that, their app will start generating one-time passwords for them.

Logging in with 2FA becomes straightforward. You verify both the password and the one-time password from the authenticator app:

@app.post("/login")
async def login(username: str, password: str, otp: str):
    # Verify the password
    user = get_user(username)
    if not user or not verify_password(password, user.password):
        raise HTTPException(status_code=401, detail="Invalid username or password")
    
    # Verify the one-time password
    totp = pyotp.TOTP(user.secret_key)
    if not totp.verify(otp):
        raise HTTPException(status_code=401, detail="Invalid one-time password")
    
    return {"message": "Logged in successfully"}

Users might want to toggle 2FA on and off. For that, we need a couple of extra endpoints:

@app.put("/auth/otp/enable")
async def enable_otp(user: User = Depends(get_current_user)):
    user.otp_enabled = True
    return {"message": "2FA enabled successfully"}

@app.put("/auth/otp/disable")
async def disable_otp(user: User = Depends(get_current_user)):
    user.otp_enabled = False
    return {"message": "2FA disabled successfully"}

And that’s how you go about integrating 2FA in FastAPI. This setup enhances your app’s security by making it harder for anyone with just a password to gain access. Remember, app security doesn’t stop here. Keep everything up to date, and consider adding more security measures like rate limiting and IP blocking to shield your app further. It’s all about staying one step ahead!

Keywords: FastAPI, 2FA, two-factor authentication, web app security, pyotp, QR code, Pydantic, Google Authenticator, user signup, one-time password



Similar Posts
Blog Image
7 Powerful Python Async Libraries Every Developer Should Know

Discover 7 powerful Python async libraries for efficient concurrent programming. Learn how asyncio, aiohttp, uvloop, trio, FastAPI, aiomysql, and asyncpg help build high-performance applications with practical code examples and expert insights.

Blog Image
The Ultimate Guide to Marshmallow Context for Smart Serialization

Marshmallow Context enhances data serialization in Python, allowing dynamic adjustments based on context. It enables flexible schemas for APIs, inheritance, and complex data handling, improving code reusability and maintainability.

Blog Image
Is FastAPI the Magical Solution for Building Super-Fast APIs?

FastAPI: The Python Powerhouse Turning High-Performance APIs into a Breeze

Blog Image
Are Background Tasks the Secret Sauce to Supercharge Your FastAPI Web Applications?

Keeping Your Web App Nimble with FastAPI Background Tasks

Blog Image
6 Essential Python Libraries for Geospatial Analysis and Mapping Projects

Transform location data into actionable insights with 6 essential Python geospatial libraries. Learn GeoPandas, Shapely, Rasterio & more for spatial analysis.

Blog Image
Top 6 Python Cryptography Libraries: A Developer's Guide to Secure Coding

Discover Python's top cryptography libraries: PyCryptodome, cryptography, pyOpenSSL, bcrypt, PyNaCl, and hashlib. Learn their strengths and use cases for secure development. Boost your app's security now!