Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

python 3.x - FastAPI masking field

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.

question from:https://stackoverflow.com/questions/65933711/fastapi-masking-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...