我遵循 FastAPI web site 上的安全教程
以具有以下端点结束:
@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"}
导致以下招摇:
我的问题: 有没有一种简单的方法来屏蔽密码字段?所以我看不到纯文本? 就像我们可以使用授权按钮一样。
答案 0 :(得分:1)
您可以使用来自 Pydantic 的 SecretStr
。它只是将 {"format": "password"}
添加到您的 OpenAPI 架构中。
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())
您将拥有这个,有关更多信息,请参阅 documentation
答案 1 :(得分:1)
根据@Yagiz 的回答,这是有效的:
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,
)