[Python] FastAPI OAuth2PasswordBearer JWT authorization not working in Swagger UI

Discussão em 'Python' iniciado por Stack, Agosto 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write login and registration routes with JWT (routes/auth.py):

    from fastapi import Depends, APIRouter, HTTPException
    from sqlalchemy.orm import Session
    from app.schemas.user import UserCreate, UserOut
    from app.models.user import User
    from app.dependencies import get_db
    from app.auth.auth import hash_password, verify_password, create_access_token, oauth2_scheme
    from fastapi.security import OAuth2PasswordRequestForm
    from typing import Annotated

    router = APIRouter(prefix='/auth', tags=['auth'])

    @router.post("/register", response_model=UserOut)
    def register(user: UserCreate, db: Session = Depends(get_db)):
    db_user = db.query(User).filter_by(email=user.email).first()
    if db_user:
    raise HTTPException(status_code=400, detail="Email already registered")
    hashed = hash_password(user.password)
    new_user = User(email=user.email, hashed_password=hashed)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user

    @router.post("/login")
    def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()], db: Session = Depends(get_db)):
    db_user = db.query(User).filter_by(email=form_data.username).first()
    if not db_user or not verify_password(form_data.password, db_user.hashed_password):
    raise HTTPException(status_code=400, detail="Incorrect email or password")
    token = create_access_token({'sub': str(db_user.id)})
    return {'access_token': token, 'token_type': 'bearer'}


    There is my auth/auth.py file with all the auth functions:

    from datetime import datetime, timedelta

    from jose import jwt, JWTError
    from passlib.context import CryptContext
    from fastapi.security import OAuth2PasswordBearer
    from sqlalchemy.orm import Session
    from app.dependencies import get_db
    from fastapi import Depends, HTTPException, status

    from app.models.user import User

    SECRET_KEY = 'SPASTI'
    ALGORITHM = 'HS256'
    ACCESS_TOKEN_EXPIRE_MINUTES = 30б

    pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login')


    def hash_password(password: str):
    return pwd_context.hash(password)

    def verify_password(plain, hashed):
    return pwd_context.verify(plain, hashed)

    def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({'exp': expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

    def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED,
    detail='Could not validate credentials',
    headers={'WWW-Authenticate': 'Bearer'}
    )

    try:
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    user_id: int = int(payload.get('sub'))
    if user_id is None:
    raise credentials_exception
    except JWTError:
    raise credentials_exception

    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
    raise credentials_exception
    return user


    I do can register and I can login with my E-mail and password and I get the token in auth/login route, but when I try to authorize using SwaggerUI 'Authorize' button, I get this error: Auth error Error: Not Found I have also noticed that I've created OAuth2PasswordBearer with right tokenUrl:eek:auth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login'), but the authorization window on my /docs SwaggerUI page shows that my tokenUrl is /login, despite me updating the code and restarting the server. What can I do in this situation?

    Continue reading...

Compartilhe esta Página