OAuth 2.0 works on the principle of tokens. A client application requests an access token from an authorization server on behalf of a resource owner (the user). The access token is then used to access the protected resources on the resource server.
There are four main roles in OAuth 2.0:
FastAPI is built on top of Starlette for the web parts and Pydantic for data validation. It uses Python type hints to provide automatic data validation, serialization, and documentation generation.
First, you need to install FastAPI and python - jose[cryptography]
for handling JWT (JSON Web Tokens) which are commonly used in OAuth 2.0.
pip install fastapi "python-jose[cryptography]" uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from pydantic import BaseModel
# Secret key for signing the JWT
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# OAuth2 scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class TokenData(BaseModel):
username: str | None = None
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
return token_data
app = FastAPI()
@app.get("/protected")
async def protected_route(current_user: TokenData = Depends(get_current_user)):
return {"message": f"Hello, {current_user.username}! This is a protected route."}
uvicorn main:app --reload
In a real - world scenario, the client application should obtain the user’s consent before requesting an access token. This can be done by redirecting the user to the authorization server’s consent page.
The secret key used for signing JWTs should be kept secret. In a production environment, it is recommended to use environment variables to store the secret key.
import os
SECRET_KEY = os.getenv("SECRET_KEY")
Set an appropriate expiration time for access tokens. Short - lived access tokens reduce the risk of token misuse if they are compromised.
Proper error handling should be implemented in both the authorization server and the resource server. For example, when a token is invalid, the resource server should return a 401 Unauthorized response.
Implementing OAuth 2.0 with FastAPI provides a powerful way to build secure and scalable APIs. By understanding the fundamental concepts, following the usage methods, and applying common and best practices, developers can ensure that their applications are protected against unauthorized access. OAuth 2.0’s flexibility and FastAPI’s performance make them a great combination for modern web development.