Tag Archives: Python

Control Access to a FastAPI App

Controlling access to a FastAPI app typically involves implementing authentication and authorization mechanisms. Here are some **decent approaches** to achieve this:

## 1. Authentication

– **OAuth2 with Password (and Bearer)**

    – Use FastAPI’s built-in support for OAuth2 for handling user login and issuing JWT tokens.

    – Users authenticate by providing a username and password, and receive a token which they then include in the Authorization header for subsequent API requests.

– **API Key**

    – Require clients to include a secret API key (in headers or query parameters) with each request.

    – Simple but less user-friendly and secure than OAuth2/JWT.

– **Session Authentication**

    – Use cookie-based sessions for traditional web apps.

## 2. Authorization

– **Role-Based Access Control (RBAC)**

    – Assign users roles (like admin, user, guest) and restrict certain endpoints or actions based on the user’s role.

– **Resource-Based Permissions**

    – Check user-specific access for resources (e.g., users can only access their own data).

## 3. Implementation in FastAPI

Example of using OAuth2/JWT bearer authentication:

“`python

from fastapi import FastAPI, Depends, HTTPException, status

from fastapi.security import OAuth2PasswordBearer

from jose import JWTError, jwt

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=”token”)

def verify_token(token: str = Depends(oauth2_scheme)):

    # Add your logic to verify JWT token here

    try:

        payload = jwt.decode(token, “your_secret_key”, algorithms=[“HS256”])

        return payload

    except JWTError:

        raise HTTPException(status_code=401, detail=”Invalid token”)

@app.get(“/protected-route”)

def protected_route(user=Depends(verify_token)):

    return {“message”: “You have access!”}

“`

## 4. Third-Party Libraries

– **fastapi-users**

Provides pluggable user authentication, registration, password management, and more.

– **Authlib**

Flexible library for implementing OAuth and JWT.

## 5. Additional Tips

– Always use HTTPS in production to protect credentials in transit.

– Regularly update dependencies to keep security patches up to date.

– Use environment variables to store secrets (never commit secrets in code).

This approach ensures robust access control suitable for both web and API-based FastAPI apps.

SQLAlchemy

SQLAlchemy is an ORM that allows interacting with DB using Python objects instead of writing raw SQL queries. Which in turn allows for developing Python solutions more in it’s own without having to jump out into SQL.

In addition, SQLAlchemy supports SQLite, PostgreSQL, MySQL and many many other DBs. Which takes yet another layer of abstraction for the development.

– manzoor

Build-a-App

  1. Primary Goal / Objective – “Learn to Program” in Python. The emphasis is on “Programming” / “Software Development” and not on “Python”.
  2. Supporting Goal / Objective – Build and Make Available (publicly) an Application Desktop and Mobile (preferably native for both iOS and Android). The purpose of the supporting goal is to

To Learn:

  1. Programming (starting with Python, but the objective is to learn “Programming” not to learn to “Program in Python” ONLY)
  2. Modern Application – Mobile is definitely one of the objective
  3. Publish an App (in the App Store and Marketplace)

– manzoor

  • Python
  • CoffeeScript
  • JavaScript
  • Ruby
  • Ruby on Rails
  • HTML5
  • Java

External Links

PIL in virtualenv in Ubuntu v11.04

Ubuntu is running in a VM running in Virtual Box on a Mac

Issue: PIL does NOT have JPEG support
Solution: Find and Install libjpeg (more specifically libjpeg-dev) before building / deploying PIL
My issue was that I had already built / deployed PIL before I got libjpeg. So, for me the solution was:
  • Uninstall PIL
  • Figure out where libjpeg was deployed – (/usr/lib/x86
– manzoor