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