Coverage for docs_src/security/tutorial005_an_py310.py: 100%
94 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-09 09:16 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-09 09:16 +0000
1from datetime import datetime, timedelta, timezone 1abcd
2from typing import Annotated 1abcd
4import jwt 1abcd
5from fastapi import Depends, FastAPI, HTTPException, Security, status 1abcd
6from fastapi.security import ( 1abcd
7 OAuth2PasswordBearer,
8 OAuth2PasswordRequestForm,
9 SecurityScopes,
10)
11from jwt.exceptions import InvalidTokenError 1abcd
12from passlib.context import CryptContext 1abcd
13from pydantic import BaseModel, ValidationError 1abcd
15# to get a string like this run:
16# openssl rand -hex 32
17SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" 1abcd
18ALGORITHM = "HS256" 1abcd
19ACCESS_TOKEN_EXPIRE_MINUTES = 30 1abcd
22fake_users_db = { 1abcd
23 "johndoe": {
24 "username": "johndoe",
25 "full_name": "John Doe",
26 "email": "johndoe@example.com",
27 "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
28 "disabled": False,
29 },
30 "alice": {
31 "username": "alice",
32 "full_name": "Alice Chains",
33 "email": "alicechains@example.com",
34 "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
35 "disabled": True,
36 },
37}
40class Token(BaseModel): 1abcd
41 access_token: str 1abcd
42 token_type: str 1abcd
45class TokenData(BaseModel): 1abcd
46 username: str | None = None 1abcd
47 scopes: list[str] = [] 1abcd
50class User(BaseModel): 1abcd
51 username: str 1abcd
52 email: str | None = None 1abcd
53 full_name: str | None = None 1abcd
54 disabled: bool | None = None 1abcd
57class UserInDB(User): 1abcd
58 hashed_password: str 1abcd
61pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") 1abcd
63oauth2_scheme = OAuth2PasswordBearer( 1abcd
64 tokenUrl="token",
65 scopes={"me": "Read information about the current user.", "items": "Read items."},
66)
68app = FastAPI() 1abcd
71def verify_password(plain_password, hashed_password): 1abcd
72 return pwd_context.verify(plain_password, hashed_password) 1yKeqfmr4zLgshnt5AMiujov6BNkwlpx7
75def get_password_hash(password): 1abcd
76 return pwd_context.hash(password) 189!#
79def get_user(db, username: str): 1abcd
80 if username in db: 1yKSeqfmrCDzLTgshntEFAMUiujovGHBNVkwlpxIJ
81 user_dict = db[username] 1yKeqfmrzLgshntAMiujovBNkwlpx
82 return UserInDB(**user_dict) 1yKeqfmrzLgshntAMiujovBNkwlpx
85def authenticate_user(fake_db, username: str, password: str): 1abcd
86 user = get_user(fake_db, username) 1yKSeqfmrzLTgshntAMUiujovBNVkwlpx
87 if not user: 1yKSeqfmrzLTgshntAMUiujovBNVkwlpx
88 return False 1STUV
89 if not verify_password(password, user.hashed_password): 1yKeqfmrzLgshntAMiujovBNkwlpx
90 return False 1KLMN
91 return user 1yeqfmrzgshntAiujovBkwlpx
94def create_access_token(data: dict, expires_delta: timedelta | None = None): 1abcd
95 to_encode = data.copy() 10yeqfmr1zgshnt2Aiujov3Bkwlpx
96 if expires_delta: 10yeqfmr1zgshnt2Aiujov3Bkwlpx
97 expire = datetime.now(timezone.utc) + expires_delta 1yeqfmrzgshntAiujovBkwlpx
98 else:
99 expire = datetime.now(timezone.utc) + timedelta(minutes=15) 10123
100 to_encode.update({"exp": expire}) 10yeqfmr1zgshnt2Aiujov3Bkwlpx
101 encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 10yeqfmr1zgshnt2Aiujov3Bkwlpx
102 return encoded_jwt 10yeqfmr1zgshnt2Aiujov3Bkwlpx
105async def get_current_user( 1abcd
106 security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
107):
108 if security_scopes.scopes: 1WeqfmrOCDXgshntPEFYiujovQGHZkwlpxRIJ
109 authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' 1WefmrOCDXghntPEFYijovQGHZklpxRIJ
110 else:
111 authenticate_value = "Bearer" 1qsuw
112 credentials_exception = HTTPException( 1WeqfmrOCDXgshntPEFYiujovQGHZkwlpxRIJ
113 status_code=status.HTTP_401_UNAUTHORIZED,
114 detail="Could not validate credentials",
115 headers={"WWW-Authenticate": authenticate_value},
116 )
117 try: 1WeqfmrOCDXgshntPEFYiujovQGHZkwlpxRIJ
118 payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) 1WeqfmrOCDXgshntPEFYiujovQGHZkwlpxRIJ
119 username = payload.get("sub") 1eqfmrOCDgshntPEFiujovQGHkwlpxRIJ
120 if username is None: 1eqfmrOCDgshntPEFiujovQGHkwlpxRIJ
121 raise credentials_exception 1OPQR
122 scope: str = payload.get("scope", "") 1eqfmrCDgshntEFiujovGHkwlpxIJ
123 token_scopes = scope.split(" ") 1eqfmrCDgshntEFiujovGHkwlpxIJ
124 token_data = TokenData(scopes=token_scopes, username=username) 1eqfmrCDgshntEFiujovGHkwlpxIJ
125 except (InvalidTokenError, ValidationError): 1WOXPYQZR
126 raise credentials_exception 1WXYZ
127 user = get_user(fake_users_db, username=token_data.username) 1eqfmrCDgshntEFiujovGHkwlpxIJ
128 if user is None: 1eqfmrCDgshntEFiujovGHkwlpxIJ
129 raise credentials_exception 1CDEFGHIJ
130 for scope in security_scopes.scopes: 1eqfmrgshntiujovkwlpx
131 if scope not in token_data.scopes: 1efmrghntijovklpx
132 raise HTTPException( 1rtvx
133 status_code=status.HTTP_401_UNAUTHORIZED,
134 detail="Not enough permissions",
135 headers={"WWW-Authenticate": authenticate_value},
136 )
137 return user 1eqfmgshniujokwlp
140async def get_current_active_user( 1abcd
141 current_user: Annotated[User, Security(get_current_user, scopes=["me"])],
142):
143 if current_user.disabled: 1efmghnijoklp
144 raise HTTPException(status_code=400, detail="Inactive user") 1mnop
145 return current_user 1efghijkl
148@app.post("/token") 1abcd
149async def login_for_access_token( 1abcd
150 form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
151) -> Token:
152 user = authenticate_user(fake_users_db, form_data.username, form_data.password) 1yKSeqfmrzLTgshntAMUiujovBNVkwlpx
153 if not user: 1yKSeqfmrzLTgshntAMUiujovBNVkwlpx
154 raise HTTPException(status_code=400, detail="Incorrect username or password") 1KSLTMUNV
155 access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) 1yeqfmrzgshntAiujovBkwlpx
156 access_token = create_access_token( 1yeqfmrzgshntAiujovBkwlpx
157 data={"sub": user.username, "scope": " ".join(form_data.scopes)},
158 expires_delta=access_token_expires,
159 )
160 return Token(access_token=access_token, token_type="bearer") 1yeqfmrzgshntAiujovBkwlpx
163@app.get("/users/me/", response_model=User) 1abcd
164async def read_users_me( 1abcd
165 current_user: Annotated[User, Depends(get_current_active_user)],
166):
167 return current_user 1fhjl
170@app.get("/users/me/items/") 1abcd
171async def read_own_items( 1abcd
172 current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])],
173):
174 return [{"item_id": "Foo", "owner": current_user.username}] 1egik
177@app.get("/status/") 1abcd
178async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]): 1abcd
179 return {"status": "ok"} 1qsuw