0
0
FastAPIframework~5 mins

Bearer token handling in FastAPI

Choose your learning style9 modes available
Introduction

Bearer token handling lets your FastAPI app check who is making a request. It helps keep your app safe by allowing only users with a valid token to access certain parts.

When you want to protect API routes so only logged-in users can use them.
When your app needs to check user identity without asking for username and password every time.
When you build an app that talks to other services and needs to send a token to prove it is allowed.
When you want to easily add security to your API using standard token methods.
Syntax
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}

OAuth2PasswordBearer is a helper that extracts the bearer token from the request header.

The Depends function tells FastAPI to use the token from the request automatically.

Examples
This sets up the way to get the token from the request header.
FastAPI
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
This example shows how to get the token inside a route handler.
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
async def read_current_user(token: str = Depends(oauth2_scheme)):
    return {"token_received": token}
This example checks if the token is correct and denies access if not.
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/secure-data")
async def secure_data(token: str = Depends(oauth2_scheme)):
    if token != "expected_token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return {"data": "This is protected"}
Sample Program

This FastAPI app has one protected route. It expects a bearer token in the request header. If the token is not exactly "mysecrettoken", it returns an error. Otherwise, it shows a success message with the token.

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
    if token != "mysecrettoken":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or missing token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return {"message": "Access granted with token: " + token}
OutputSuccess
Important Notes

Always use HTTPS to keep bearer tokens safe during transmission.

The tokenUrl parameter in OAuth2PasswordBearer is the URL where clients get tokens; it does not have to be implemented for token extraction to work.

Bearer tokens are usually sent in the header as: Authorization: Bearer <token>

Summary

Bearer token handling helps secure API routes by checking tokens sent by clients.

FastAPI's OAuth2PasswordBearer makes it easy to get the token from requests.

You can check the token value and reject requests without valid tokens.