Skip to main content

Authentication and Authorization Basics for APIs: JWT (Introduction)

Following our lesson on CORS (Cross-Origin Resource Sharing) in FastAPI APIs, this article introduces Authentication and Authorization Basics for APIs: JWT (Introduction). Securing your API is crucial, and JSON Web Tokens (JWT) are a popular way to handle authentication.


📚 Prerequisites

  • A running FastAPI application.
  • Understanding of dependency injection.

🎯 Article Outline: What You'll Master

  • Foundational Theory: The difference between authentication and authorization.
  • Core Concepts: What a JSON Web Token (JWT) is and how it works.
  • Practical Application: Creating a simple login endpoint that returns a JWT.
  • Securing Endpoints: Creating a dependency to protect endpoints.

🧠 Section 1: The Core Concepts of Authentication, Authorization, and JWT

  • Authentication: The process of verifying who a user is.
  • Authorization: The process of verifying what a user has permission to do.
  • JWT (JSON Web Token): A compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

💻 Section 2: Deep Dive - Implementation and Walkthrough

FastAPI has excellent support for security and authentication. Let's create a simple example using JWT.

First, install the necessary libraries:

pip install python-jose[cryptography] passlib[bcrypt]

Now, let's create a simple authentication system.

# main.py
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext

# Security constants
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

app = FastAPI()

# ... (user database and functions to get user, create token, etc. would go here)

@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
# In a real app, you would verify the username and password here
# For simplicity, we'll just create a token for the user
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": form_data.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}

async def get_current_user(token: str = Depends(oauth2_scheme)):
# This is where you would decode the token and get the user
# For simplicity, we'll just return a dummy user
return {"username": "testuser"}

@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_user

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

💡 Conclusion & Key Takeaways

You've learned the basics of authentication and authorization in a web API and seen a simple implementation of JWT-based authentication in FastAPI.

Let's summarize the key takeaways:

  • Authentication verifies identity, while authorization verifies permissions.
  • JWT is a standard for creating access tokens.
  • FastAPI's security utilities make it easy to implement authentication.

➡️ Next Steps

This concludes our series on building web APIs with FastAPI. In the next chapter, we will dive into data science with Python.


Glossary

  • Authentication: The process of verifying a user's identity.
  • Authorization: The process of verifying a user's permissions.
  • JWT: JSON Web Token.
  • OAuth2: An authorization framework.

Further Reading