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
Python on Microcontrollers: A Comprehensive Guide to Writing Embedded Software with MicroPython

MicroPython brings Python to microcontrollers, enabling rapid prototyping and easy hardware control. It supports various boards, offers interactive REPL, and simplifies tasks like I2C communication and web servers. Perfect for IoT and robotics projects.

Blog Image
5 Essential Python Performance Monitoring Tools for Code Optimization in 2024

Discover 5 essential Python performance monitoring tools to optimize your code. Learn to use cProfile, line_profiler, Scalene, pyViz, and py-spy with practical examples. Boost your app's efficiency today. #Python #DevOps

Blog Image
NestJS and gRPC: Building High-Performance Inter-Service Communication

NestJS and gRPC combine for high-performance microservices. NestJS offers modular architecture, while gRPC provides fast inter-service communication. Together, they enable efficient, scalable applications with streaming capabilities and strong testing support.

Blog Image
5 Essential Python Testing Libraries: A Complete Guide with Code Examples (2024)

Discover essential Python testing libraries for robust code validation. Learn to implement Pytest, unittest, nose2, doctest, and coverage.py with practical examples and best practices. #PythonTesting #CodeQuality

Blog Image
Which Python Web Framework Will You Choose: Flask or Django?

Choosing Between Flask and Django: Navigating Web Development Frameworks for Your Next Project

Blog Image
Breaking Down Marshmallow’s Field Metadata for Better API Documentation

Marshmallow's field metadata enhances API documentation, providing rich context for developers. It allows for detailed field descriptions, example values, and nested schemas, making APIs more user-friendly and easier to integrate.