================ CODE SNIPPETS ================ TITLE: User Authentication and Retrieval (FastAPI) DESCRIPTION: Provides functions to retrieve user data from a database (simulated here with a dictionary) and to authenticate users by comparing provided credentials with stored hashed passwords. This is a core part of the authentication flow. SOURCE: https://fastapi.tiangolo.com/ru/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } # (Import UserInDB and verify_password from previous snippets) def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Functions to retrieve user data from a fake database and authenticate users by verifying their username and password. It returns a `UserDB` object upon successful authentication. SOURCE: https://fastapi.tiangolo.com/ru/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import Dict, Union # Assuming User and UserInDB models are defined elsewhere # from models import User, UserInDB fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } def get_user(db: Dict[str, Dict], username: str) -> Union["UserInDB", None]: if username in db: user_dict = db[username] # Assuming UserInDB(**user_dict) correctly instantiates the model return UserInDB(**user_dict) return None def authenticate_user(fake_db: Dict[str, Dict], username: str, password: str) -> Union["UserInDB", None]: user = get_user(fake_db, username) if not user: return False # Assuming verify_password is defined elsewhere if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: POST /token - User Authentication DESCRIPTION: Authenticates a user with username and password, and returns an access token upon successful authentication. SOURCE: https://fastapi.tiangolo.com/ko/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with username and password, and returns an access token upon successful authentication. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (str) - Required - The username for authentication. - **password** (str) - Required - The password for authentication. ### Request Example ```json { "username": "johndoe", "password": "secretpassword" } ``` ### Response #### Success Response (200) - **access_token** (str) - The generated access token. - **token_type** (str) - The type of token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqb2huZG9lIiwiZXhwIjoxNjczMzA3MTY4fQ.example_token", "token_type": "bearer" } ``` #### Error Response (401) - **detail** (str) - "Incorrect username or password" ``` -------------------------------- TITLE: User Authentication and Authorization (Python) DESCRIPTION: Functions for verifying passwords, hashing passwords, retrieving users from a fake database, and authenticating users. It also includes functions to get the current user and the current active user. SOURCE: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt LANGUAGE: Python CODE: ``` fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } password_hash = PasswordHash.recommended() def verify_password(plain_password, hashed_password): return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): return password_hash.hash(password) def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user async def get_current_active_user(current_user: User = Depends(get_current_user)): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user ``` -------------------------------- TITLE: Python: User Authentication and Retrieval Functions DESCRIPTION: Implements functions for retrieving user data from a fake database and authenticating users by verifying their credentials against stored hashed passwords. The `get_user` function retrieves a user by username, and `authenticate_user` checks both username and password. SOURCE: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: User Authentication API DESCRIPTION: This endpoint allows users to authenticate by providing their username and password. It returns an access token upon successful authentication. SOURCE: https://fastapi.tiangolo.com/zh/tutorial/security/simple-oauth2 LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with username and password and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (str) - Required - The user's username. - **password** (str) - Required - The user's password. ### Request Example { "username": "johndoe", "password": "secret" } ### Response #### Success Response (200) - **access_token** (str) - The access token for the user. - **token_type** (str) - The type of token, typically 'bearer'. #### Response Example { "access_token": "johndoe", "token_type": "bearer" } #### Error Response (400) - **detail** (str) - Description of the error, e.g., 'Incorrect username or password'. ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Provides functions to authenticate users against a fake database and retrieve user information. It uses the previously defined password verification to check credentials. This is a core component for verifying user identities before granting access. SOURCE: https://fastapi.tiangolo.com/ja/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import List, Union, Dict, Any from pydantic import BaseModel # Assume User and UserInDB models are defined elsewhere fake_users_db: Dict[str, Dict[str, Any]] = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } # Assume verify_password is defined as shown previously def get_user(db: Dict[str, Dict[str, Any]], username: str) -> Union[UserInDB, None]: if username in db: user_dict = db[username] return UserInDB(**user_dict) return None def authenticate_user(fake_db: Dict[str, Dict[str, Any]], username: str, password: str) -> Union[UserInDB, None]: user = get_user(fake_db, username) if not user: return None if not verify_password(password, user.hashed_password): return None return user ``` -------------------------------- TITLE: User Authentication and Token Generation DESCRIPTION: Authenticates a user with provided credentials and generates an access token upon successful authentication. Requires username and password. SOURCE: https://fastapi.tiangolo.com/zh/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (str) - Required - The username for authentication. - **password** (str) - Required - The password for authentication. - **scopes** (str) - Optional - The scopes to be associated with the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": "me items" } ``` ### Response #### Success Response (200) - **access_token** (str) - The generated access token. - **token_type** (str) - The type of the token (e.g., "bearer"). #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... "token_type": "bearer" } ``` #### Error Response (400) - **detail** (str) - "Incorrect username or password" ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Demonstrates functions to retrieve user data from a database and authenticate users by verifying their credentials against a hashed password. The `authenticate_user` function checks both user existence and password validity. SOURCE: https://fastapi.tiangolo.com/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import Dict, Union from pydantic import BaseModel # Assume fake_users_db and verify_password are defined elsewhere fake_users_db: Dict[str, Dict] = { "johndoe": {"username": "johndoe", "hashed_password": "..."}, "alice": {"username": "alice", "hashed_password": "..."} } def verify_password(plain_password, hashed_password): # Placeholder for actual password verification logic return True class User(BaseModel): username: str hashed_password: str def get_user(db: Dict[str, Dict], username: str) -> Union[User, None]: if username in db: user_dict = db[username] return User(**user_dict) return None def authenticate_user(fake_db: Dict[str, Dict], username: str, password: str) -> Union[User, None]: user = get_user(fake_db, username) if not user: return None if not verify_password(password, user.hashed_password): return None return user ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: Handles user authentication and generates access tokens. It accepts username and password, and returns an access token upon successful authentication. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with username and password and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. - **scopes** (array of strings) - Optional - The scopes to be associated with the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": ["me", "items"] } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated access token. - **token_type** (string) - The type of the token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer" } ``` ``` -------------------------------- TITLE: User Authentication Logic DESCRIPTION: This function authenticates a user by checking their username and password against the provided database. It returns the user object if authentication is successful, otherwise `False`. SOURCE: https://fastapi.tiangolo.com/de/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: This endpoint handles user authentication by verifying credentials and issuing an access token. It accepts username and password in the request form. SOURCE: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with provided credentials and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Query Parameters None #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Request Example ``` { "username": "johndoe", "password": "secretpassword" } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated JWT access token. - **token_type** (string) - The type of the token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqb2huZG9lIiwiZXhwIjoxNjczNzM1MjAwfQ.some_signature", "token_type": "bearer" } ``` #### Error Response (401) - **detail** (string) - "Incorrect username or password" - **headers** - {"WWW-Authenticate": "Bearer"} #### Error Response Example (401) ```json { "detail": "Incorrect username or password" } ``` ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Functions to retrieve user data from a database (simulated here) and authenticate users by verifying their credentials against stored hashed passwords. Returns a User object upon successful authentication. SOURCE: https://fastapi.tiangolo.com/ru/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import Union from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes from pydantic import BaseModel, EmailStr from typing_extensions import Annotated # ... (other imports and models) fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: Python User Retrieval and Authentication Logic DESCRIPTION: Includes functions to retrieve user data from a database (simulated by a dictionary) and to authenticate users by verifying their username and password against the stored hashed password. SOURCE: https://fastapi.tiangolo.com/vi/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` from typing import Union from pydantic import BaseModel # Assuming User and UserInDB models are defined as above # Assuming fake_users_db is defined as above class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: HTTP Authentication Schemes DESCRIPTION: Covers standard HTTP authentication methods like Bearer and Basic authentication. SOURCE: https://fastapi.tiangolo.com/em/tutorial/security LANGUAGE: APIDOC CODE: ``` ## HTTP Authentication Schemes ### Description FastAPI supports common HTTP authentication schemes, allowing you to secure your endpoints using established protocols. ### Schemes - **`bearer`**: This scheme uses the `Authorization` HTTP header with the format `Bearer `. It's frequently employed in conjunction with OAuth2 implementations. - **Basic Authentication**: Standard HTTP Basic authentication using username and password. - **Digest Authentication**: A more secure challenge-response authentication mechanism than Basic authentication. ### Integration These schemes can be easily integrated into your FastAPI application to protect specific routes or the entire API. ``` -------------------------------- TITLE: Python: User Authentication Logic DESCRIPTION: Handles the authentication of a user by checking their credentials against a provided database. It relies on `get_user` and `verify_password` functions. SOURCE: https://fastapi.tiangolo.com/zh/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import Dict, Any # Assume get_user and verify_password are defined # def get_user(db: Dict[str, Dict[str, Any]], username: str): # # ... implementation ... # def verify_password(plain_password: str, hashed_password: str) -> bool: # # ... implementation ... def authenticate_user(fake_db: Dict[str, Dict[str, Any]], username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: User Authentication API DESCRIPTION: Handles user authentication and token generation. Accepts username and password for login, and returns an access token upon successful authentication. SOURCE: https://fastapi.tiangolo.com/ru/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with provided credentials and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. - **scopes** (string) - Optional - A space-separated string of scopes requested for the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": "me items" } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated JWT access token. - **token_type** (string) - The type of the token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer" } ``` #### Error Response (400) - **detail** (string) - "Incorrect username or password" if authentication fails. ``` -------------------------------- TITLE: User Authentication and Password Hashing DESCRIPTION: Defines Pydantic models for user data and handles password hashing and verification using `pwdlib`. It includes functions to hash passwords and verify plain text passwords against their hashed versions. SOURCE: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` from pydantic import BaseModel from pwdlib import PasswordHash class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): hashed_password: str password_hash = PasswordHash.recommended() def verify_password(plain_password, hashed_password): return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): return password_hash.hash(password) ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: These functions handle user authentication and retrieval within the application. `get_user` fetches user details from a database (simulated here with a dictionary), and `authenticate_user` verifies a username and password against the stored hashed password. This is a core part of the login process. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes from pydantic import BaseModel, ValidationError from typing import Union, Annotated from passlib.context import CryptContext from jose import JWTError, jwt from jose.exceptions import InvalidTokenError # ... (other imports and definitions like fake_users_db, User, UserInDB) def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: This endpoint allows users to authenticate and obtain an access token. It requires a username and password, and returns a bearer token upon successful authentication. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with provided credentials and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. - **scopes** (array of strings) - Optional - The scopes requested for the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": ["me", "items"] } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated access token. - **token_type** (string) - The type of token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...".", "token_type": "bearer" } ``` ``` -------------------------------- TITLE: FastAPI Endpoints with User Authentication (Python) DESCRIPTION: Demonstrates FastAPI endpoints that require user authentication. The `/users/me/` endpoint retrieves the current authenticated user, while `/users/me/items/` requires specific scopes ('items') for access. It uses `Depends` and `Security` for dependency injection of the authenticated user. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from fastapi import FastAPI, Depends, Security from typing import List, Union # Assuming User, get_current_active_user, get_current_user are defined elsewhere app = FastAPI() @app.get("/users/me/", response_model=User) async def read_users_me( current_user: User = Depends(get_current_active_user), ): return current_user @app.get("/users/me/items/") async def read_own_items( current_user: User = Security(get_current_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] @app.get("/status/") async def read_system_status(current_user: User = Depends(get_current_user)): return {"status": "ok"} ``` -------------------------------- TITLE: Password Hashing and Verification Utility DESCRIPTION: Provides functions to securely hash passwords using Argon2id and verify plain text passwords against a hash. It uses the `pwdlib` library for cryptographic operations. Ensure `pwdlib` is installed. SOURCE: https://fastapi.tiangolo.com/fa/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` from datetime import datetime, timedelta, timezone import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: Union[str, None] = None class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str password_hash = PasswordHash.recommended() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") app = FastAPI() def verify_password(plain_password, hashed_password): return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): return password_hash.hash(password) def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Implements functions to retrieve user data from a 'fake' database and authenticate users by verifying their credentials against hashed passwords. It returns a `UserDB` object upon successful authentication. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import Dict, Union # Assuming UserDB and User models are defined elsewhere fake_users_db: Dict[str, Dict[str, Union[str, bool]]] def get_user(db: Dict[str, Dict[str, Union[str, bool]]], username: str): if username in db: user_dict = db[username] # Assuming UserDB is a Pydantic model or similar return UserDB(**user_dict) return None def authenticate_user(fake_db: Dict[str, Dict[str, Union[str, bool]]], username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: Handles user authentication and issues access tokens. SOURCE: https://fastapi.tiangolo.com/uk/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with username and password, returning an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (str) - Required - The user's username. - **password** (str) - Required - The user's password. - **scopes** (list[str]) - Optional - The scopes to request for the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": ["me", "items"] } ``` ### Response #### Success Response (200) - **access_token** (str) - The generated access token. - **token_type** (str) - The type of the token (e.g., "bearer"). #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer" } ``` ``` -------------------------------- TITLE: Password Hashing and Verification (Python) DESCRIPTION: Implements functions to securely hash passwords using argon2id and verify them against stored hashes. It relies on the 'pwdlib' library. This is crucial for secure user authentication. SOURCE: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` from datetime import datetime, timedelta, timezone from typing import Annotated, Union import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: Union[str, None] = None class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str password_hash = PasswordHash.recommended() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") app = FastAPI() def verify_password(plain_password, hashed_password): return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): return password_hash.hash(password) def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: raise credentials_exception return user async def get_current_active_user(current_user: User = Depends(get_current_user)): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user @app.post("/token") async def login_for_access_token( form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: 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 Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) async def read_users_me(current_user: User = Depends(get_current_active_user)): return current_user @app.get("/users/me/items/") async def read_own_items(current_user: User = Depends(get_current_active_user)): return [{"item_id": "Foo", "owner": current_user.username}] ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: Endpoint for authenticating users and obtaining access tokens. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with their username and password and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. - **scopes** (array of strings) - Optional - The scopes to request for the access token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": ["me", "items"] } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated access token. - **token_type** (string) - The type of the token, typically "bearer". #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqb2huZG9lIiwic2NvcGUiOiJtZSBpdGVtcyIsImV4cCI6MTcwMzA0MjY4Nn0.abcdefghijklmnopqrstuvwxyz1234567890 "token_type": "bearer" } ``` ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Functions to retrieve user data from a fake database and authenticate users by comparing provided credentials with stored hashed passwords. This relies on the `verify_password` function and a user database. SOURCE: https://fastapi.tiangolo.com/fr/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from pydantic import BaseModel from typing import Union, List class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: Token Authentication API DESCRIPTION: Handles user authentication and issues access tokens. SOURCE: https://fastapi.tiangolo.com/pt/advanced/security/oauth2-scopes LANGUAGE: APIDOC CODE: ``` ## POST /token ### Description Authenticates a user with provided credentials and returns an access token. ### Method POST ### Endpoint /token ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. - **scopes** (array[string]) - Optional - Scopes for the token. ### Request Example ```json { "username": "johndoe", "password": "secretpassword", "scopes": ["me", "items"] } ``` ### Response #### Success Response (200) - **access_token** (string) - The generated access token. - **token_type** (string) - The type of token (e.g., "bearer"). #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer" } ``` ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Functions to retrieve user data from a database and authenticate users by comparing provided credentials with stored hashed passwords. It defines Pydantic models for user data. SOURCE: https://fastapi.tiangolo.com/es/advanced/security/oauth2-scopes LANGUAGE: python CODE: ``` from typing import List, Union from pydantic import BaseModel class User(BaseModel): username: str email: Union[str, None] = None full_name: Union[str, None] = None disabled: Union[bool, None] = None class UserInDB(User): hashed_password: str fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ``` -------------------------------- TITLE: User Authentication and Retrieval (Python) DESCRIPTION: Provides functions to retrieve user data from a database and authenticate users by verifying their credentials against stored hashed passwords. It defines Pydantic models for user data. The `get_user` function retrieves user details, and `authenticate_user` performs the login check. SOURCE: https://fastapi.tiangolo.com/ru/tutorial/security/oauth2-jwt LANGUAGE: python CODE: ``` from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pydantic import BaseModel # Assume password_hash and verify_password are defined as above # Assume fake_users_db is defined class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, user.hashed_password): return False return user ```