๐Ÿ“ Fastapi

OAuth2 Bearer in FastAPI

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
387
๐Ÿ†
Level
Expert

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 Authentication in FastAPI

Covered topics: Installation, Configuration, Password and Token Utilities, Token Endpoint.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 305
๐Ÿ“

Middleware and CORS in FastAPI

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 330
๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 296
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

FastAPI: From First Route to an AI-Powered Site Open course curriculum