Coverage for docs_src / security / tutorial007_an_py310.py: 100%
19 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1import secrets 1abc
2from typing import Annotated 1abc
4from fastapi import Depends, FastAPI, HTTPException, status 1abc
5from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abc
7app = FastAPI() 1abc
9security = HTTPBasic() 1abc
12def get_current_username( 1abc
13 credentials: Annotated[HTTPBasicCredentials, Depends(security)],
14):
15 current_username_bytes = credentials.username.encode("utf8") 1dgheijfkl
16 correct_username_bytes = b"stanleyjobson" 1dgheijfkl
17 is_correct_username = secrets.compare_digest( 1dgheijfkl
18 current_username_bytes, correct_username_bytes
19 )
20 current_password_bytes = credentials.password.encode("utf8") 1dgheijfkl
21 correct_password_bytes = b"swordfish" 1dgheijfkl
22 is_correct_password = secrets.compare_digest( 1dgheijfkl
23 current_password_bytes, correct_password_bytes
24 )
25 if not (is_correct_username and is_correct_password): 1dgheijfkl
26 raise HTTPException( 1ghijkl
27 status_code=status.HTTP_401_UNAUTHORIZED,
28 detail="Incorrect username or password",
29 headers={"WWW-Authenticate": "Basic"},
30 )
31 return credentials.username 1def
34@app.get("/users/me") 1abc
35def read_current_user(username: Annotated[str, Depends(get_current_username)]): 1abc
36 return {"username": username} 1def