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
How Can You Make Your FastAPI Super Fast and Reliable Using Redis?

Guardians of the API Galaxy: Boosting FastAPI with Rate Limiting and Caching

Blog Image
How Can You Launch Your FastAPI App into the Clouds Without Breaking a Sweat?

Launching FastAPI to the Cloud: Simplified Steps for GCP and AWS Integration

Blog Image
6 Powerful Python Libraries for Detecting Memory Leaks in Your Code

Discover 6 powerful Python tools to identify and fix memory leaks. Learn practical strategies for efficient memory management in long-running applications. Prevent RAM issues today. #PythonDevelopment #MemoryOptimization

Blog Image
What Magical Trick Makes FastAPI Lightning-Fast?

Turbo-Charge Your FastAPI with Asynchronous Routes for Blazing Performance

Blog Image
Why FastAPI and RabbitMQ Could Be Your Next Secret Weapon in Web Development?

Crafting a High-Performance Web Symphony with FastAPI, RabbitMQ, and Celery

Blog Image
Schema Inheritance in Marshmallow: Reuse and Extend Like a Python Ninja

Schema inheritance in Marshmallow allows reuse of common fields and methods. It enhances code organization, reduces repetition, and enables customization. Base schemas can be extended, fields overridden, and multiple inheritance used for flexibility in Python serialization.