FastAPI masking field

Viewed 1237

I follow the tutorial about Security on FastAPI web site

Ending by having the following endpoint:

@app.post("/token", response_model= Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

Resulting in the following swagger:

enter image description here

My question: Is there a simple way to mask the password field? So I do not see it in plain text? Like we can do with authorize button.

2 Answers

You can use SecretStr from Pydantic. It simply adds {"format": "password"} to your OpenAPI schema.

from fastapi import FastAPI, Depends
from pydantic import BaseModel, SecretStr


class User(BaseModel):
    username: str
    password: SecretStr 

app = FastAPI()


@app.post("/user")
async def create_user(user: User = Depends()):
    print(user.password.get_secret_value())

You will have this, for more see the documentation

enter image description here

According to @Yagiz answer, this works:


class CustomOAuth2PasswordRequestForm(OAuth2PasswordRequestForm):
    def __init__(
            self,
            grant_type: str = Form(..., regex="password"),
            username: str = Form(...),
            password: SecretStr = Form(...),
            scope: str = Form(""),
            client_id: Optional[str] = Form(None),
            client_secret: Optional[str] = Form(None),
    ):
        super().__init__(
            grant_type=grant_type,
            username=username,
            password=password,
            scope=scope,
            client_id=client_id,
            client_secret=client_secret,
        )
Related