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
Versioning APIs with Marshmallow: How to Maintain Backward Compatibility

API versioning with Marshmallow enables smooth updates while maintaining backward compatibility. It supports multiple schema versions, allowing gradual feature rollout without disrupting existing integrations. Clear documentation and thorough testing are crucial.

Blog Image
Secure FastAPI Deployment: HTTPS, SSL, and Nginx for Bulletproof APIs

FastAPI, HTTPS, SSL, and Nginx combine to create secure, high-performance web applications. FastAPI offers easy API development, while HTTPS and SSL provide encryption. Nginx acts as a reverse proxy, enhancing security and performance.

Blog Image
Supercharge Your API: FastAPI and Tortoise-ORM for NoSQL Databases

FastAPI with Tortoise-ORM enhances API performance for NoSQL databases. Async operations, flexible schemas, and efficient querying enable scalable, high-speed APIs. Leverage NoSQL strengths for optimal results.

Blog Image
7 Powerful Python Libraries for Data Visualization: From Matplotlib to HoloViews

Discover 7 powerful Python libraries for data visualization. Learn to create compelling, interactive charts and graphs. Enhance your data analysis skills today!

Blog Image
NestJS + Redis: Implementing Distributed Caching for Blazing Fast Performance

Distributed caching with NestJS and Redis boosts app speed. Store frequent data in memory for faster access. Implement with CacheModule, use Redis for storage. Handle cache invalidation and consistency. Significant performance improvements possible.

Blog Image
Why Is FastAPI the Ultimate Choice for Building Secure Multi-Tenant SaaS Applications?

FastAPI Powers Efficient and Secure Multi-Tenant SaaS Solutions