📝 Fastapi

OAuth2 Bearer in FastAPI

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
105
📊
Level
Article

OAuth2PasswordBearer is FastAPI’s Bearer token authentication scheme.

OAuth2 scheme

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException

# tokenUrl — the URL used to obtain a token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")

Login form (OAuth2PasswordRequestForm)

from fastapi import APIRouter
from fastapi.security import OAuth2PasswordRequestForm

router = APIRouter(prefix="/auth")

@router.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
    # form_data.username
    # form_data.password
    user = authenticate(form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")

    token = create_token(user.id)
    return {
        "access_token": token,
        "token_type": "bearer",  # required!
    }

Using the token in a request

# Obtain a token
curl -X POST /auth/token \
  -F "username=user" \
  -F "password=pass"

# Use the token
curl /api/tasks/ \
  -H "Authorization: Bearer eyJhbGci..."

Extracting the token in an endpoint

@app.get("/tasks/")
async def list_tasks(token: str = Depends(oauth2_scheme)):
    # token — raw token string
    user = decode_token(token)
    return get_tasks(user)

Optional authentication

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)

@app.get("/tasks/")
def list_tasks(token: str | None = Depends(oauth2_scheme)):
    if token:
        user = decode_token(token)
        return get_user_tasks(user)
    return get_public_tasks()

Refresh tokens

class TokenResponse(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str = "bearer"
    expires_in: int

@router.post("/token", response_model=TokenResponse)
def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate(form_data.username, form_data.password)
    return {
        "access_token": create_access_token(user.id),
        "refresh_token": create_refresh_token(user.id),
        "expires_in": 1800,
    }

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

JWT Tokens with python-jose

python-jose is a library for working with JSON Web Tokens (JWT).

📅 30.06.2026 👁️ 112
📝

Middleware and CORS in FastAPI

Allows browser clients to make requests to an API from a different domain.

📅 30.06.2026 👁️ 90
📝

HTTPException in FastAPI

Охватываемые темы: Basic Usage, Status Codes, Error Details, Custom Headers.

📅 30.06.2026 👁️ 91

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!