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="user@example.com", 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
Can You Unlock the Search Power of Your Web Apps with FastAPI and Elasticsearch?

Unlocking Superior Web Application Capabilities with FastAPI and Elasticsearch Magic

Blog Image
Ready to Master FastAPI Security with Pydantic Secrets?

Mastering FastAPI Security: From Secrets to Safe Sessions and Secure Logging

Blog Image
Unleash Marshmallow’s True Power: Master Nested Schemas for Complex Data Structures

Marshmallow: Python library for handling complex data. Nested schemas simplify serialization of hierarchical structures. Versatile for JSON APIs and databases. Supports validation, transformation, and inheritance. Efficient for large datasets. Practice key to mastery.

Blog Image
Unlock Python's Memory Magic: Boost Speed and Save RAM with Memoryviews

Python memoryviews offer efficient handling of large binary data without copying. They act as windows into memory, allowing direct access and manipulation. Memoryviews support the buffer protocol, enabling use with various Python objects. They excel in reshaping data, network protocols, and file I/O. Memoryviews can boost performance in scenarios involving large arrays, structured data, and memory-mapped files.

Blog Image
Could Connection Pooling and Indexing Be the Secret Sauce for Your FastAPI Performance?

Streamline Your FastAPI Performance with Connection Pooling and Database Indexing

Blog Image
7 Essential Python Best Practices for Clean, Efficient Code

Discover 7 essential Python best practices for cleaner, more efficient code. Learn to write maintainable, readable, and scalable Python projects. Improve your coding skills today!