OAuth2 scopes

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can use OAuth2 scopes directly with FastAPI, they are integrated to work seamlessly.

This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).

OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. They use it to provide specific permissions to users and applications.

Every time you “log in with” Facebook, Google, GitHub, Microsoft, Twitter, that application is using OAuth2 with scopes.

In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your FastAPI application.

Warning

This is a more or less advanced section. If you are just starting, you can skip it.

You don’t necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.

But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.

Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.

In many cases, OAuth2 with scopes can be an overkill.

But if you know you need it, or you are curious, keep reading.

OAuth2 scopes and OpenAPI

The OAuth2 specification defines “scopes” as a list of strings separated by spaces.

The content of each of these strings can have any format, but should not contain spaces.

These scopes represent “permissions”.

In OpenAPI (e.g. the API docs), you can define “security schemes”.

When one of these security schemes uses OAuth2, you can also declare and use scopes.

Each “scope” is just a string (without spaces).

They are normally used to declare specific security permissions, for example:

  • users:read or users:write are common examples.
  • instagram_basic is used by Facebook / Instagram.
  • https://www.googleapis.com/auth/drive is used by Google.

Info

In OAuth2 a “scope” is just a string that declares a specific permission required.

It doesn’t matter if it has other characters like : or if it is a URL.

Those details are implementation specific.

For OAuth2 they are just strings.

Global view

First, let’s quickly see the parts that change from the examples in the main Tutorial - User Guide for OAuth2 with Password (and hashing), Bearer with JWT tokens. Now using OAuth2 scopes:

Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import Annotated, List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. from typing_extensions import Annotated
  13. # to get a string like this run:
  14. # openssl rand -hex 32
  15. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  16. ALGORITHM = "HS256"
  17. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  18. fake_users_db = {
  19. "johndoe": {
  20. "username": "johndoe",
  21. "full_name": "John Doe",
  22. "email": "johndoe@example.com",
  23. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  24. "disabled": False,
  25. },
  26. "alice": {
  27. "username": "alice",
  28. "full_name": "Alice Chains",
  29. "email": "alicechains@example.com",
  30. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  31. "disabled": True,
  32. },
  33. }
  34. class Token(BaseModel):
  35. access_token: str
  36. token_type: str
  37. class TokenData(BaseModel):
  38. username: Union[str, None] = None
  39. scopes: List[str] = []
  40. class User(BaseModel):
  41. username: str
  42. email: Union[str, None] = None
  43. full_name: Union[str, None] = None
  44. disabled: Union[bool, None] = None
  45. class UserInDB(User):
  46. hashed_password: str
  47. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  48. oauth2_scheme = OAuth2PasswordBearer(
  49. tokenUrl="token",
  50. scopes={"me": "Read information about the current user.", "items": "Read items."},
  51. )
  52. app = FastAPI()
  53. def verify_password(plain_password, hashed_password):
  54. return pwd_context.verify(plain_password, hashed_password)
  55. def get_password_hash(password):
  56. return pwd_context.hash(password)
  57. def get_user(db, username: str):
  58. if username in db:
  59. user_dict = db[username]
  60. return UserInDB(**user_dict)
  61. def authenticate_user(fake_db, username: str, password: str):
  62. user = get_user(fake_db, username)
  63. if not user:
  64. return False
  65. if not verify_password(password, user.hashed_password):
  66. return False
  67. return user
  68. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  69. to_encode = data.copy()
  70. if expires_delta:
  71. expire = datetime.utcnow() + expires_delta
  72. else:
  73. expire = datetime.utcnow() + timedelta(minutes=15)
  74. to_encode.update({"exp": expire})
  75. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  76. return encoded_jwt
  77. async def get_current_user(
  78. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  79. ):
  80. if security_scopes.scopes:
  81. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  82. else:
  83. authenticate_value = "Bearer"
  84. credentials_exception = HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail="Could not validate credentials",
  87. headers={"WWW-Authenticate": authenticate_value},
  88. )
  89. try:
  90. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  91. username: str = payload.get("sub")
  92. if username is None:
  93. raise credentials_exception
  94. token_scopes = payload.get("scopes", [])
  95. token_data = TokenData(scopes=token_scopes, username=username)
  96. except (JWTError, ValidationError):
  97. raise credentials_exception
  98. user = get_user(fake_users_db, username=token_data.username)
  99. if user is None:
  100. raise credentials_exception
  101. for scope in security_scopes.scopes:
  102. if scope not in token_data.scopes:
  103. raise HTTPException(
  104. status_code=status.HTTP_401_UNAUTHORIZED,
  105. detail="Not enough permissions",
  106. headers={"WWW-Authenticate": authenticate_value},
  107. )
  108. return user
  109. async def get_current_active_user(
  110. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  111. ):
  112. if current_user.disabled:
  113. raise HTTPException(status_code=400, detail="Inactive user")
  114. return current_user
  115. @app.post("/token", response_model=Token)
  116. async def login_for_access_token(
  117. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  118. ):
  119. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  120. if not user:
  121. raise HTTPException(status_code=400, detail="Incorrect username or password")
  122. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  123. access_token = create_access_token(
  124. data={"sub": user.username, "scopes": form_data.scopes},
  125. expires_delta=access_token_expires,
  126. )
  127. return {"access_token": access_token, "token_type": "bearer"}
  128. @app.get("/users/me/", response_model=User)
  129. async def read_users_me(
  130. current_user: Annotated[User, Depends(get_current_active_user)]
  131. ):
  132. return current_user
  133. @app.get("/users/me/items/")
  134. async def read_own_items(
  135. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  136. ):
  137. return [{"item_id": "Foo", "owner": current_user.username}]
  138. @app.get("/status/")
  139. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  140. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from fastapi import Depends, FastAPI, HTTPException, Security, status
  3. from fastapi.security import (
  4. OAuth2PasswordBearer,
  5. OAuth2PasswordRequestForm,
  6. SecurityScopes,
  7. )
  8. from jose import JWTError, jwt
  9. from passlib.context import CryptContext
  10. from pydantic import BaseModel, ValidationError
  11. # to get a string like this run:
  12. # openssl rand -hex 32
  13. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  14. ALGORITHM = "HS256"
  15. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  16. fake_users_db = {
  17. "johndoe": {
  18. "username": "johndoe",
  19. "full_name": "John Doe",
  20. "email": "johndoe@example.com",
  21. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  22. "disabled": False,
  23. },
  24. "alice": {
  25. "username": "alice",
  26. "full_name": "Alice Chains",
  27. "email": "alicechains@example.com",
  28. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  29. "disabled": True,
  30. },
  31. }
  32. class Token(BaseModel):
  33. access_token: str
  34. token_type: str
  35. class TokenData(BaseModel):
  36. username: str | None = None
  37. scopes: list[str] = []
  38. class User(BaseModel):
  39. username: str
  40. email: str | None = None
  41. full_name: str | None = None
  42. disabled: bool | None = None
  43. class UserInDB(User):
  44. hashed_password: str
  45. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  46. oauth2_scheme = OAuth2PasswordBearer(
  47. tokenUrl="token",
  48. scopes={"me": "Read information about the current user.", "items": "Read items."},
  49. )
  50. app = FastAPI()
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. def get_password_hash(password):
  54. return pwd_context.hash(password)
  55. def get_user(db, username: str):
  56. if username in db:
  57. user_dict = db[username]
  58. return UserInDB(**user_dict)
  59. def authenticate_user(fake_db, username: str, password: str):
  60. user = get_user(fake_db, username)
  61. if not user:
  62. return False
  63. if not verify_password(password, user.hashed_password):
  64. return False
  65. return user
  66. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  67. to_encode = data.copy()
  68. if expires_delta:
  69. expire = datetime.utcnow() + expires_delta
  70. else:
  71. expire = datetime.utcnow() + timedelta(minutes=15)
  72. to_encode.update({"exp": expire})
  73. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  74. return encoded_jwt
  75. async def get_current_user(
  76. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  77. ):
  78. if security_scopes.scopes:
  79. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  80. else:
  81. authenticate_value = "Bearer"
  82. credentials_exception = HTTPException(
  83. status_code=status.HTTP_401_UNAUTHORIZED,
  84. detail="Could not validate credentials",
  85. headers={"WWW-Authenticate": authenticate_value},
  86. )
  87. try:
  88. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  89. username: str = payload.get("sub")
  90. if username is None:
  91. raise credentials_exception
  92. token_scopes = payload.get("scopes", [])
  93. token_data = TokenData(scopes=token_scopes, username=username)
  94. except (JWTError, ValidationError):
  95. raise credentials_exception
  96. user = get_user(fake_users_db, username=token_data.username)
  97. if user is None:
  98. raise credentials_exception
  99. for scope in security_scopes.scopes:
  100. if scope not in token_data.scopes:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail="Not enough permissions",
  104. headers={"WWW-Authenticate": authenticate_value},
  105. )
  106. return user
  107. async def get_current_active_user(
  108. current_user: User = Security(get_current_user, scopes=["me"])
  109. ):
  110. if current_user.disabled:
  111. raise HTTPException(status_code=400, detail="Inactive user")
  112. return current_user
  113. @app.post("/token", response_model=Token)
  114. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  115. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  116. if not user:
  117. raise HTTPException(status_code=400, detail="Incorrect username or password")
  118. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  119. access_token = create_access_token(
  120. data={"sub": user.username, "scopes": form_data.scopes},
  121. expires_delta=access_token_expires,
  122. )
  123. return {"access_token": access_token, "token_type": "bearer"}
  124. @app.get("/users/me/", response_model=User)
  125. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  126. return current_user
  127. @app.get("/users/me/items/")
  128. async def read_own_items(
  129. current_user: User = Security(get_current_active_user, scopes=["items"])
  130. ):
  131. return [{"item_id": "Foo", "owner": current_user.username}]
  132. @app.get("/status/")
  133. async def read_system_status(current_user: User = Depends(get_current_user)):
  134. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Now let’s review those changes step by step.

OAuth2 Security scheme

The first change is that now we are declaring the OAuth2 security scheme with two available scopes, me and items.

The scopes parameter receives a dict with each scope as a key and the description as the value:

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import Annotated, List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. from typing_extensions import Annotated
  13. # to get a string like this run:
  14. # openssl rand -hex 32
  15. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  16. ALGORITHM = "HS256"
  17. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  18. fake_users_db = {
  19. "johndoe": {
  20. "username": "johndoe",
  21. "full_name": "John Doe",
  22. "email": "johndoe@example.com",
  23. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  24. "disabled": False,
  25. },
  26. "alice": {
  27. "username": "alice",
  28. "full_name": "Alice Chains",
  29. "email": "alicechains@example.com",
  30. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  31. "disabled": True,
  32. },
  33. }
  34. class Token(BaseModel):
  35. access_token: str
  36. token_type: str
  37. class TokenData(BaseModel):
  38. username: Union[str, None] = None
  39. scopes: List[str] = []
  40. class User(BaseModel):
  41. username: str
  42. email: Union[str, None] = None
  43. full_name: Union[str, None] = None
  44. disabled: Union[bool, None] = None
  45. class UserInDB(User):
  46. hashed_password: str
  47. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  48. oauth2_scheme = OAuth2PasswordBearer(
  49. tokenUrl="token",
  50. scopes={"me": "Read information about the current user.", "items": "Read items."},
  51. )
  52. app = FastAPI()
  53. def verify_password(plain_password, hashed_password):
  54. return pwd_context.verify(plain_password, hashed_password)
  55. def get_password_hash(password):
  56. return pwd_context.hash(password)
  57. def get_user(db, username: str):
  58. if username in db:
  59. user_dict = db[username]
  60. return UserInDB(**user_dict)
  61. def authenticate_user(fake_db, username: str, password: str):
  62. user = get_user(fake_db, username)
  63. if not user:
  64. return False
  65. if not verify_password(password, user.hashed_password):
  66. return False
  67. return user
  68. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  69. to_encode = data.copy()
  70. if expires_delta:
  71. expire = datetime.utcnow() + expires_delta
  72. else:
  73. expire = datetime.utcnow() + timedelta(minutes=15)
  74. to_encode.update({"exp": expire})
  75. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  76. return encoded_jwt
  77. async def get_current_user(
  78. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  79. ):
  80. if security_scopes.scopes:
  81. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  82. else:
  83. authenticate_value = "Bearer"
  84. credentials_exception = HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail="Could not validate credentials",
  87. headers={"WWW-Authenticate": authenticate_value},
  88. )
  89. try:
  90. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  91. username: str = payload.get("sub")
  92. if username is None:
  93. raise credentials_exception
  94. token_scopes = payload.get("scopes", [])
  95. token_data = TokenData(scopes=token_scopes, username=username)
  96. except (JWTError, ValidationError):
  97. raise credentials_exception
  98. user = get_user(fake_users_db, username=token_data.username)
  99. if user is None:
  100. raise credentials_exception
  101. for scope in security_scopes.scopes:
  102. if scope not in token_data.scopes:
  103. raise HTTPException(
  104. status_code=status.HTTP_401_UNAUTHORIZED,
  105. detail="Not enough permissions",
  106. headers={"WWW-Authenticate": authenticate_value},
  107. )
  108. return user
  109. async def get_current_active_user(
  110. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  111. ):
  112. if current_user.disabled:
  113. raise HTTPException(status_code=400, detail="Inactive user")
  114. return current_user
  115. @app.post("/token", response_model=Token)
  116. async def login_for_access_token(
  117. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  118. ):
  119. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  120. if not user:
  121. raise HTTPException(status_code=400, detail="Incorrect username or password")
  122. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  123. access_token = create_access_token(
  124. data={"sub": user.username, "scopes": form_data.scopes},
  125. expires_delta=access_token_expires,
  126. )
  127. return {"access_token": access_token, "token_type": "bearer"}
  128. @app.get("/users/me/", response_model=User)
  129. async def read_users_me(
  130. current_user: Annotated[User, Depends(get_current_active_user)]
  131. ):
  132. return current_user
  133. @app.get("/users/me/items/")
  134. async def read_own_items(
  135. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  136. ):
  137. return [{"item_id": "Foo", "owner": current_user.username}]
  138. @app.get("/status/")
  139. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  140. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from fastapi import Depends, FastAPI, HTTPException, Security, status
  3. from fastapi.security import (
  4. OAuth2PasswordBearer,
  5. OAuth2PasswordRequestForm,
  6. SecurityScopes,
  7. )
  8. from jose import JWTError, jwt
  9. from passlib.context import CryptContext
  10. from pydantic import BaseModel, ValidationError
  11. # to get a string like this run:
  12. # openssl rand -hex 32
  13. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  14. ALGORITHM = "HS256"
  15. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  16. fake_users_db = {
  17. "johndoe": {
  18. "username": "johndoe",
  19. "full_name": "John Doe",
  20. "email": "johndoe@example.com",
  21. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  22. "disabled": False,
  23. },
  24. "alice": {
  25. "username": "alice",
  26. "full_name": "Alice Chains",
  27. "email": "alicechains@example.com",
  28. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  29. "disabled": True,
  30. },
  31. }
  32. class Token(BaseModel):
  33. access_token: str
  34. token_type: str
  35. class TokenData(BaseModel):
  36. username: str | None = None
  37. scopes: list[str] = []
  38. class User(BaseModel):
  39. username: str
  40. email: str | None = None
  41. full_name: str | None = None
  42. disabled: bool | None = None
  43. class UserInDB(User):
  44. hashed_password: str
  45. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  46. oauth2_scheme = OAuth2PasswordBearer(
  47. tokenUrl="token",
  48. scopes={"me": "Read information about the current user.", "items": "Read items."},
  49. )
  50. app = FastAPI()
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. def get_password_hash(password):
  54. return pwd_context.hash(password)
  55. def get_user(db, username: str):
  56. if username in db:
  57. user_dict = db[username]
  58. return UserInDB(**user_dict)
  59. def authenticate_user(fake_db, username: str, password: str):
  60. user = get_user(fake_db, username)
  61. if not user:
  62. return False
  63. if not verify_password(password, user.hashed_password):
  64. return False
  65. return user
  66. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  67. to_encode = data.copy()
  68. if expires_delta:
  69. expire = datetime.utcnow() + expires_delta
  70. else:
  71. expire = datetime.utcnow() + timedelta(minutes=15)
  72. to_encode.update({"exp": expire})
  73. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  74. return encoded_jwt
  75. async def get_current_user(
  76. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  77. ):
  78. if security_scopes.scopes:
  79. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  80. else:
  81. authenticate_value = "Bearer"
  82. credentials_exception = HTTPException(
  83. status_code=status.HTTP_401_UNAUTHORIZED,
  84. detail="Could not validate credentials",
  85. headers={"WWW-Authenticate": authenticate_value},
  86. )
  87. try:
  88. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  89. username: str = payload.get("sub")
  90. if username is None:
  91. raise credentials_exception
  92. token_scopes = payload.get("scopes", [])
  93. token_data = TokenData(scopes=token_scopes, username=username)
  94. except (JWTError, ValidationError):
  95. raise credentials_exception
  96. user = get_user(fake_users_db, username=token_data.username)
  97. if user is None:
  98. raise credentials_exception
  99. for scope in security_scopes.scopes:
  100. if scope not in token_data.scopes:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail="Not enough permissions",
  104. headers={"WWW-Authenticate": authenticate_value},
  105. )
  106. return user
  107. async def get_current_active_user(
  108. current_user: User = Security(get_current_user, scopes=["me"])
  109. ):
  110. if current_user.disabled:
  111. raise HTTPException(status_code=400, detail="Inactive user")
  112. return current_user
  113. @app.post("/token", response_model=Token)
  114. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  115. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  116. if not user:
  117. raise HTTPException(status_code=400, detail="Incorrect username or password")
  118. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  119. access_token = create_access_token(
  120. data={"sub": user.username, "scopes": form_data.scopes},
  121. expires_delta=access_token_expires,
  122. )
  123. return {"access_token": access_token, "token_type": "bearer"}
  124. @app.get("/users/me/", response_model=User)
  125. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  126. return current_user
  127. @app.get("/users/me/items/")
  128. async def read_own_items(
  129. current_user: User = Security(get_current_active_user, scopes=["items"])
  130. ):
  131. return [{"item_id": "Foo", "owner": current_user.username}]
  132. @app.get("/status/")
  133. async def read_system_status(current_user: User = Depends(get_current_user)):
  134. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.

And you will be able to select which scopes you want to give access to: me and items.

This is the same mechanism used when you give permissions while logging in with Facebook, Google, GitHub, etc:

OAuth2 scopes - 图1

JWT token with scopes

Now, modify the token path operation to return the scopes requested.

We are still using the same OAuth2PasswordRequestForm. It includes a property scopes with a list of str, with each scope it received in the request.

And we return the scopes as part of the JWT token.

Danger

For simplicity, here we are just adding the scopes received directly to the token.

But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import Annotated, List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. from typing_extensions import Annotated
  13. # to get a string like this run:
  14. # openssl rand -hex 32
  15. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  16. ALGORITHM = "HS256"
  17. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  18. fake_users_db = {
  19. "johndoe": {
  20. "username": "johndoe",
  21. "full_name": "John Doe",
  22. "email": "johndoe@example.com",
  23. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  24. "disabled": False,
  25. },
  26. "alice": {
  27. "username": "alice",
  28. "full_name": "Alice Chains",
  29. "email": "alicechains@example.com",
  30. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  31. "disabled": True,
  32. },
  33. }
  34. class Token(BaseModel):
  35. access_token: str
  36. token_type: str
  37. class TokenData(BaseModel):
  38. username: Union[str, None] = None
  39. scopes: List[str] = []
  40. class User(BaseModel):
  41. username: str
  42. email: Union[str, None] = None
  43. full_name: Union[str, None] = None
  44. disabled: Union[bool, None] = None
  45. class UserInDB(User):
  46. hashed_password: str
  47. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  48. oauth2_scheme = OAuth2PasswordBearer(
  49. tokenUrl="token",
  50. scopes={"me": "Read information about the current user.", "items": "Read items."},
  51. )
  52. app = FastAPI()
  53. def verify_password(plain_password, hashed_password):
  54. return pwd_context.verify(plain_password, hashed_password)
  55. def get_password_hash(password):
  56. return pwd_context.hash(password)
  57. def get_user(db, username: str):
  58. if username in db:
  59. user_dict = db[username]
  60. return UserInDB(**user_dict)
  61. def authenticate_user(fake_db, username: str, password: str):
  62. user = get_user(fake_db, username)
  63. if not user:
  64. return False
  65. if not verify_password(password, user.hashed_password):
  66. return False
  67. return user
  68. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  69. to_encode = data.copy()
  70. if expires_delta:
  71. expire = datetime.utcnow() + expires_delta
  72. else:
  73. expire = datetime.utcnow() + timedelta(minutes=15)
  74. to_encode.update({"exp": expire})
  75. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  76. return encoded_jwt
  77. async def get_current_user(
  78. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  79. ):
  80. if security_scopes.scopes:
  81. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  82. else:
  83. authenticate_value = "Bearer"
  84. credentials_exception = HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail="Could not validate credentials",
  87. headers={"WWW-Authenticate": authenticate_value},
  88. )
  89. try:
  90. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  91. username: str = payload.get("sub")
  92. if username is None:
  93. raise credentials_exception
  94. token_scopes = payload.get("scopes", [])
  95. token_data = TokenData(scopes=token_scopes, username=username)
  96. except (JWTError, ValidationError):
  97. raise credentials_exception
  98. user = get_user(fake_users_db, username=token_data.username)
  99. if user is None:
  100. raise credentials_exception
  101. for scope in security_scopes.scopes:
  102. if scope not in token_data.scopes:
  103. raise HTTPException(
  104. status_code=status.HTTP_401_UNAUTHORIZED,
  105. detail="Not enough permissions",
  106. headers={"WWW-Authenticate": authenticate_value},
  107. )
  108. return user
  109. async def get_current_active_user(
  110. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  111. ):
  112. if current_user.disabled:
  113. raise HTTPException(status_code=400, detail="Inactive user")
  114. return current_user
  115. @app.post("/token", response_model=Token)
  116. async def login_for_access_token(
  117. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  118. ):
  119. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  120. if not user:
  121. raise HTTPException(status_code=400, detail="Incorrect username or password")
  122. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  123. access_token = create_access_token(
  124. data={"sub": user.username, "scopes": form_data.scopes},
  125. expires_delta=access_token_expires,
  126. )
  127. return {"access_token": access_token, "token_type": "bearer"}
  128. @app.get("/users/me/", response_model=User)
  129. async def read_users_me(
  130. current_user: Annotated[User, Depends(get_current_active_user)]
  131. ):
  132. return current_user
  133. @app.get("/users/me/items/")
  134. async def read_own_items(
  135. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  136. ):
  137. return [{"item_id": "Foo", "owner": current_user.username}]
  138. @app.get("/status/")
  139. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  140. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from fastapi import Depends, FastAPI, HTTPException, Security, status
  3. from fastapi.security import (
  4. OAuth2PasswordBearer,
  5. OAuth2PasswordRequestForm,
  6. SecurityScopes,
  7. )
  8. from jose import JWTError, jwt
  9. from passlib.context import CryptContext
  10. from pydantic import BaseModel, ValidationError
  11. # to get a string like this run:
  12. # openssl rand -hex 32
  13. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  14. ALGORITHM = "HS256"
  15. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  16. fake_users_db = {
  17. "johndoe": {
  18. "username": "johndoe",
  19. "full_name": "John Doe",
  20. "email": "johndoe@example.com",
  21. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  22. "disabled": False,
  23. },
  24. "alice": {
  25. "username": "alice",
  26. "full_name": "Alice Chains",
  27. "email": "alicechains@example.com",
  28. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  29. "disabled": True,
  30. },
  31. }
  32. class Token(BaseModel):
  33. access_token: str
  34. token_type: str
  35. class TokenData(BaseModel):
  36. username: str | None = None
  37. scopes: list[str] = []
  38. class User(BaseModel):
  39. username: str
  40. email: str | None = None
  41. full_name: str | None = None
  42. disabled: bool | None = None
  43. class UserInDB(User):
  44. hashed_password: str
  45. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  46. oauth2_scheme = OAuth2PasswordBearer(
  47. tokenUrl="token",
  48. scopes={"me": "Read information about the current user.", "items": "Read items."},
  49. )
  50. app = FastAPI()
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. def get_password_hash(password):
  54. return pwd_context.hash(password)
  55. def get_user(db, username: str):
  56. if username in db:
  57. user_dict = db[username]
  58. return UserInDB(**user_dict)
  59. def authenticate_user(fake_db, username: str, password: str):
  60. user = get_user(fake_db, username)
  61. if not user:
  62. return False
  63. if not verify_password(password, user.hashed_password):
  64. return False
  65. return user
  66. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  67. to_encode = data.copy()
  68. if expires_delta:
  69. expire = datetime.utcnow() + expires_delta
  70. else:
  71. expire = datetime.utcnow() + timedelta(minutes=15)
  72. to_encode.update({"exp": expire})
  73. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  74. return encoded_jwt
  75. async def get_current_user(
  76. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  77. ):
  78. if security_scopes.scopes:
  79. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  80. else:
  81. authenticate_value = "Bearer"
  82. credentials_exception = HTTPException(
  83. status_code=status.HTTP_401_UNAUTHORIZED,
  84. detail="Could not validate credentials",
  85. headers={"WWW-Authenticate": authenticate_value},
  86. )
  87. try:
  88. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  89. username: str = payload.get("sub")
  90. if username is None:
  91. raise credentials_exception
  92. token_scopes = payload.get("scopes", [])
  93. token_data = TokenData(scopes=token_scopes, username=username)
  94. except (JWTError, ValidationError):
  95. raise credentials_exception
  96. user = get_user(fake_users_db, username=token_data.username)
  97. if user is None:
  98. raise credentials_exception
  99. for scope in security_scopes.scopes:
  100. if scope not in token_data.scopes:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail="Not enough permissions",
  104. headers={"WWW-Authenticate": authenticate_value},
  105. )
  106. return user
  107. async def get_current_active_user(
  108. current_user: User = Security(get_current_user, scopes=["me"])
  109. ):
  110. if current_user.disabled:
  111. raise HTTPException(status_code=400, detail="Inactive user")
  112. return current_user
  113. @app.post("/token", response_model=Token)
  114. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  115. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  116. if not user:
  117. raise HTTPException(status_code=400, detail="Incorrect username or password")
  118. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  119. access_token = create_access_token(
  120. data={"sub": user.username, "scopes": form_data.scopes},
  121. expires_delta=access_token_expires,
  122. )
  123. return {"access_token": access_token, "token_type": "bearer"}
  124. @app.get("/users/me/", response_model=User)
  125. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  126. return current_user
  127. @app.get("/users/me/items/")
  128. async def read_own_items(
  129. current_user: User = Security(get_current_active_user, scopes=["items"])
  130. ):
  131. return [{"item_id": "Foo", "owner": current_user.username}]
  132. @app.get("/status/")
  133. async def read_system_status(current_user: User = Depends(get_current_user)):
  134. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Declare scopes in path operations and dependencies

Now we declare that the path operation for /users/me/items/ requires the scope items.

For this, we import and use Security from fastapi.

You can use Security to declare dependencies (just like Depends), but Security also receives a parameter scopes with a list of scopes (strings).

In this case, we pass a dependency function get_current_active_user to Security (the same way we would do with Depends).

But we also pass a list of scopes, in this case with just one scope: items (it could have more).

And the dependency function get_current_active_user can also declare sub-dependencies, not only with Depends but also with Security. Declaring its own sub-dependency function (get_current_user), and more scope requirements.

In this case, it requires the scope me (it could require more than one scope).

Note

You don’t necessarily need to add different scopes in different places.

We are doing it here to demonstrate how FastAPI handles scopes declared at different levels.

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import Annotated, List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. from typing_extensions import Annotated
  13. # to get a string like this run:
  14. # openssl rand -hex 32
  15. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  16. ALGORITHM = "HS256"
  17. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  18. fake_users_db = {
  19. "johndoe": {
  20. "username": "johndoe",
  21. "full_name": "John Doe",
  22. "email": "johndoe@example.com",
  23. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  24. "disabled": False,
  25. },
  26. "alice": {
  27. "username": "alice",
  28. "full_name": "Alice Chains",
  29. "email": "alicechains@example.com",
  30. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  31. "disabled": True,
  32. },
  33. }
  34. class Token(BaseModel):
  35. access_token: str
  36. token_type: str
  37. class TokenData(BaseModel):
  38. username: Union[str, None] = None
  39. scopes: List[str] = []
  40. class User(BaseModel):
  41. username: str
  42. email: Union[str, None] = None
  43. full_name: Union[str, None] = None
  44. disabled: Union[bool, None] = None
  45. class UserInDB(User):
  46. hashed_password: str
  47. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  48. oauth2_scheme = OAuth2PasswordBearer(
  49. tokenUrl="token",
  50. scopes={"me": "Read information about the current user.", "items": "Read items."},
  51. )
  52. app = FastAPI()
  53. def verify_password(plain_password, hashed_password):
  54. return pwd_context.verify(plain_password, hashed_password)
  55. def get_password_hash(password):
  56. return pwd_context.hash(password)
  57. def get_user(db, username: str):
  58. if username in db:
  59. user_dict = db[username]
  60. return UserInDB(**user_dict)
  61. def authenticate_user(fake_db, username: str, password: str):
  62. user = get_user(fake_db, username)
  63. if not user:
  64. return False
  65. if not verify_password(password, user.hashed_password):
  66. return False
  67. return user
  68. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  69. to_encode = data.copy()
  70. if expires_delta:
  71. expire = datetime.utcnow() + expires_delta
  72. else:
  73. expire = datetime.utcnow() + timedelta(minutes=15)
  74. to_encode.update({"exp": expire})
  75. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  76. return encoded_jwt
  77. async def get_current_user(
  78. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  79. ):
  80. if security_scopes.scopes:
  81. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  82. else:
  83. authenticate_value = "Bearer"
  84. credentials_exception = HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail="Could not validate credentials",
  87. headers={"WWW-Authenticate": authenticate_value},
  88. )
  89. try:
  90. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  91. username: str = payload.get("sub")
  92. if username is None:
  93. raise credentials_exception
  94. token_scopes = payload.get("scopes", [])
  95. token_data = TokenData(scopes=token_scopes, username=username)
  96. except (JWTError, ValidationError):
  97. raise credentials_exception
  98. user = get_user(fake_users_db, username=token_data.username)
  99. if user is None:
  100. raise credentials_exception
  101. for scope in security_scopes.scopes:
  102. if scope not in token_data.scopes:
  103. raise HTTPException(
  104. status_code=status.HTTP_401_UNAUTHORIZED,
  105. detail="Not enough permissions",
  106. headers={"WWW-Authenticate": authenticate_value},
  107. )
  108. return user
  109. async def get_current_active_user(
  110. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  111. ):
  112. if current_user.disabled:
  113. raise HTTPException(status_code=400, detail="Inactive user")
  114. return current_user
  115. @app.post("/token", response_model=Token)
  116. async def login_for_access_token(
  117. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  118. ):
  119. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  120. if not user:
  121. raise HTTPException(status_code=400, detail="Incorrect username or password")
  122. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  123. access_token = create_access_token(
  124. data={"sub": user.username, "scopes": form_data.scopes},
  125. expires_delta=access_token_expires,
  126. )
  127. return {"access_token": access_token, "token_type": "bearer"}
  128. @app.get("/users/me/", response_model=User)
  129. async def read_users_me(
  130. current_user: Annotated[User, Depends(get_current_active_user)]
  131. ):
  132. return current_user
  133. @app.get("/users/me/items/")
  134. async def read_own_items(
  135. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  136. ):
  137. return [{"item_id": "Foo", "owner": current_user.username}]
  138. @app.get("/status/")
  139. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  140. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from fastapi import Depends, FastAPI, HTTPException, Security, status
  3. from fastapi.security import (
  4. OAuth2PasswordBearer,
  5. OAuth2PasswordRequestForm,
  6. SecurityScopes,
  7. )
  8. from jose import JWTError, jwt
  9. from passlib.context import CryptContext
  10. from pydantic import BaseModel, ValidationError
  11. # to get a string like this run:
  12. # openssl rand -hex 32
  13. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  14. ALGORITHM = "HS256"
  15. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  16. fake_users_db = {
  17. "johndoe": {
  18. "username": "johndoe",
  19. "full_name": "John Doe",
  20. "email": "johndoe@example.com",
  21. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  22. "disabled": False,
  23. },
  24. "alice": {
  25. "username": "alice",
  26. "full_name": "Alice Chains",
  27. "email": "alicechains@example.com",
  28. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  29. "disabled": True,
  30. },
  31. }
  32. class Token(BaseModel):
  33. access_token: str
  34. token_type: str
  35. class TokenData(BaseModel):
  36. username: str | None = None
  37. scopes: list[str] = []
  38. class User(BaseModel):
  39. username: str
  40. email: str | None = None
  41. full_name: str | None = None
  42. disabled: bool | None = None
  43. class UserInDB(User):
  44. hashed_password: str
  45. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  46. oauth2_scheme = OAuth2PasswordBearer(
  47. tokenUrl="token",
  48. scopes={"me": "Read information about the current user.", "items": "Read items."},
  49. )
  50. app = FastAPI()
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. def get_password_hash(password):
  54. return pwd_context.hash(password)
  55. def get_user(db, username: str):
  56. if username in db:
  57. user_dict = db[username]
  58. return UserInDB(**user_dict)
  59. def authenticate_user(fake_db, username: str, password: str):
  60. user = get_user(fake_db, username)
  61. if not user:
  62. return False
  63. if not verify_password(password, user.hashed_password):
  64. return False
  65. return user
  66. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  67. to_encode = data.copy()
  68. if expires_delta:
  69. expire = datetime.utcnow() + expires_delta
  70. else:
  71. expire = datetime.utcnow() + timedelta(minutes=15)
  72. to_encode.update({"exp": expire})
  73. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  74. return encoded_jwt
  75. async def get_current_user(
  76. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  77. ):
  78. if security_scopes.scopes:
  79. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  80. else:
  81. authenticate_value = "Bearer"
  82. credentials_exception = HTTPException(
  83. status_code=status.HTTP_401_UNAUTHORIZED,
  84. detail="Could not validate credentials",
  85. headers={"WWW-Authenticate": authenticate_value},
  86. )
  87. try:
  88. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  89. username: str = payload.get("sub")
  90. if username is None:
  91. raise credentials_exception
  92. token_scopes = payload.get("scopes", [])
  93. token_data = TokenData(scopes=token_scopes, username=username)
  94. except (JWTError, ValidationError):
  95. raise credentials_exception
  96. user = get_user(fake_users_db, username=token_data.username)
  97. if user is None:
  98. raise credentials_exception
  99. for scope in security_scopes.scopes:
  100. if scope not in token_data.scopes:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail="Not enough permissions",
  104. headers={"WWW-Authenticate": authenticate_value},
  105. )
  106. return user
  107. async def get_current_active_user(
  108. current_user: User = Security(get_current_user, scopes=["me"])
  109. ):
  110. if current_user.disabled:
  111. raise HTTPException(status_code=400, detail="Inactive user")
  112. return current_user
  113. @app.post("/token", response_model=Token)
  114. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  115. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  116. if not user:
  117. raise HTTPException(status_code=400, detail="Incorrect username or password")
  118. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  119. access_token = create_access_token(
  120. data={"sub": user.username, "scopes": form_data.scopes},
  121. expires_delta=access_token_expires,
  122. )
  123. return {"access_token": access_token, "token_type": "bearer"}
  124. @app.get("/users/me/", response_model=User)
  125. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  126. return current_user
  127. @app.get("/users/me/items/")
  128. async def read_own_items(
  129. current_user: User = Security(get_current_active_user, scopes=["items"])
  130. ):
  131. return [{"item_id": "Foo", "owner": current_user.username}]
  132. @app.get("/status/")
  133. async def read_system_status(current_user: User = Depends(get_current_user)):
  134. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Technical Details

Security is actually a subclass of Depends, and it has just one extra parameter that we’ll see later.

But by using Security instead of Depends, FastAPI will know that it can declare security scopes, use them internally, and document the API with OpenAPI.

But when you import Query, Path, Depends, Security and others from fastapi, those are actually functions that return special classes.

Use SecurityScopes

Now update the dependency get_current_user.

This is the one used by the dependencies above.

Here’s were we are using the same OAuth2 scheme we created before, declaring it as a dependency: oauth2_scheme.

Because this dependency function doesn’t have any scope requirements itself, we can use Depends with oauth2_scheme, we don’t have to use Security when we don’t need to specify security scopes.

We also declare a special parameter of type SecurityScopes, imported from fastapi.security.

This SecurityScopes class is similar to Request (Request was used to get the request object directly).

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import Annotated, List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. from typing_extensions import Annotated
  13. # to get a string like this run:
  14. # openssl rand -hex 32
  15. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  16. ALGORITHM = "HS256"
  17. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  18. fake_users_db = {
  19. "johndoe": {
  20. "username": "johndoe",
  21. "full_name": "John Doe",
  22. "email": "johndoe@example.com",
  23. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  24. "disabled": False,
  25. },
  26. "alice": {
  27. "username": "alice",
  28. "full_name": "Alice Chains",
  29. "email": "alicechains@example.com",
  30. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  31. "disabled": True,
  32. },
  33. }
  34. class Token(BaseModel):
  35. access_token: str
  36. token_type: str
  37. class TokenData(BaseModel):
  38. username: Union[str, None] = None
  39. scopes: List[str] = []
  40. class User(BaseModel):
  41. username: str
  42. email: Union[str, None] = None
  43. full_name: Union[str, None] = None
  44. disabled: Union[bool, None] = None
  45. class UserInDB(User):
  46. hashed_password: str
  47. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  48. oauth2_scheme = OAuth2PasswordBearer(
  49. tokenUrl="token",
  50. scopes={"me": "Read information about the current user.", "items": "Read items."},
  51. )
  52. app = FastAPI()
  53. def verify_password(plain_password, hashed_password):
  54. return pwd_context.verify(plain_password, hashed_password)
  55. def get_password_hash(password):
  56. return pwd_context.hash(password)
  57. def get_user(db, username: str):
  58. if username in db:
  59. user_dict = db[username]
  60. return UserInDB(**user_dict)
  61. def authenticate_user(fake_db, username: str, password: str):
  62. user = get_user(fake_db, username)
  63. if not user:
  64. return False
  65. if not verify_password(password, user.hashed_password):
  66. return False
  67. return user
  68. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  69. to_encode = data.copy()
  70. if expires_delta:
  71. expire = datetime.utcnow() + expires_delta
  72. else:
  73. expire = datetime.utcnow() + timedelta(minutes=15)
  74. to_encode.update({"exp": expire})
  75. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  76. return encoded_jwt
  77. async def get_current_user(
  78. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  79. ):
  80. if security_scopes.scopes:
  81. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  82. else:
  83. authenticate_value = "Bearer"
  84. credentials_exception = HTTPException(
  85. status_code=status.HTTP_401_UNAUTHORIZED,
  86. detail="Could not validate credentials",
  87. headers={"WWW-Authenticate": authenticate_value},
  88. )
  89. try:
  90. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  91. username: str = payload.get("sub")
  92. if username is None:
  93. raise credentials_exception
  94. token_scopes = payload.get("scopes", [])
  95. token_data = TokenData(scopes=token_scopes, username=username)
  96. except (JWTError, ValidationError):
  97. raise credentials_exception
  98. user = get_user(fake_users_db, username=token_data.username)
  99. if user is None:
  100. raise credentials_exception
  101. for scope in security_scopes.scopes:
  102. if scope not in token_data.scopes:
  103. raise HTTPException(
  104. status_code=status.HTTP_401_UNAUTHORIZED,
  105. detail="Not enough permissions",
  106. headers={"WWW-Authenticate": authenticate_value},
  107. )
  108. return user
  109. async def get_current_active_user(
  110. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  111. ):
  112. if current_user.disabled:
  113. raise HTTPException(status_code=400, detail="Inactive user")
  114. return current_user
  115. @app.post("/token", response_model=Token)
  116. async def login_for_access_token(
  117. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  118. ):
  119. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  120. if not user:
  121. raise HTTPException(status_code=400, detail="Incorrect username or password")
  122. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  123. access_token = create_access_token(
  124. data={"sub": user.username, "scopes": form_data.scopes},
  125. expires_delta=access_token_expires,
  126. )
  127. return {"access_token": access_token, "token_type": "bearer"}
  128. @app.get("/users/me/", response_model=User)
  129. async def read_users_me(
  130. current_user: Annotated[User, Depends(get_current_active_user)]
  131. ):
  132. return current_user
  133. @app.get("/users/me/items/")
  134. async def read_own_items(
  135. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  136. ):
  137. return [{"item_id": "Foo", "owner": current_user.username}]
  138. @app.get("/status/")
  139. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  140. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from fastapi import Depends, FastAPI, HTTPException, Security, status
  3. from fastapi.security import (
  4. OAuth2PasswordBearer,
  5. OAuth2PasswordRequestForm,
  6. SecurityScopes,
  7. )
  8. from jose import JWTError, jwt
  9. from passlib.context import CryptContext
  10. from pydantic import BaseModel, ValidationError
  11. # to get a string like this run:
  12. # openssl rand -hex 32
  13. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  14. ALGORITHM = "HS256"
  15. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  16. fake_users_db = {
  17. "johndoe": {
  18. "username": "johndoe",
  19. "full_name": "John Doe",
  20. "email": "johndoe@example.com",
  21. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  22. "disabled": False,
  23. },
  24. "alice": {
  25. "username": "alice",
  26. "full_name": "Alice Chains",
  27. "email": "alicechains@example.com",
  28. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  29. "disabled": True,
  30. },
  31. }
  32. class Token(BaseModel):
  33. access_token: str
  34. token_type: str
  35. class TokenData(BaseModel):
  36. username: str | None = None
  37. scopes: list[str] = []
  38. class User(BaseModel):
  39. username: str
  40. email: str | None = None
  41. full_name: str | None = None
  42. disabled: bool | None = None
  43. class UserInDB(User):
  44. hashed_password: str
  45. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  46. oauth2_scheme = OAuth2PasswordBearer(
  47. tokenUrl="token",
  48. scopes={"me": "Read information about the current user.", "items": "Read items."},
  49. )
  50. app = FastAPI()
  51. def verify_password(plain_password, hashed_password):
  52. return pwd_context.verify(plain_password, hashed_password)
  53. def get_password_hash(password):
  54. return pwd_context.hash(password)
  55. def get_user(db, username: str):
  56. if username in db:
  57. user_dict = db[username]
  58. return UserInDB(**user_dict)
  59. def authenticate_user(fake_db, username: str, password: str):
  60. user = get_user(fake_db, username)
  61. if not user:
  62. return False
  63. if not verify_password(password, user.hashed_password):
  64. return False
  65. return user
  66. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  67. to_encode = data.copy()
  68. if expires_delta:
  69. expire = datetime.utcnow() + expires_delta
  70. else:
  71. expire = datetime.utcnow() + timedelta(minutes=15)
  72. to_encode.update({"exp": expire})
  73. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  74. return encoded_jwt
  75. async def get_current_user(
  76. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  77. ):
  78. if security_scopes.scopes:
  79. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  80. else:
  81. authenticate_value = "Bearer"
  82. credentials_exception = HTTPException(
  83. status_code=status.HTTP_401_UNAUTHORIZED,
  84. detail="Could not validate credentials",
  85. headers={"WWW-Authenticate": authenticate_value},
  86. )
  87. try:
  88. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  89. username: str = payload.get("sub")
  90. if username is None:
  91. raise credentials_exception
  92. token_scopes = payload.get("scopes", [])
  93. token_data = TokenData(scopes=token_scopes, username=username)
  94. except (JWTError, ValidationError):
  95. raise credentials_exception
  96. user = get_user(fake_users_db, username=token_data.username)
  97. if user is None:
  98. raise credentials_exception
  99. for scope in security_scopes.scopes:
  100. if scope not in token_data.scopes:
  101. raise HTTPException(
  102. status_code=status.HTTP_401_UNAUTHORIZED,
  103. detail="Not enough permissions",
  104. headers={"WWW-Authenticate": authenticate_value},
  105. )
  106. return user
  107. async def get_current_active_user(
  108. current_user: User = Security(get_current_user, scopes=["me"])
  109. ):
  110. if current_user.disabled:
  111. raise HTTPException(status_code=400, detail="Inactive user")
  112. return current_user
  113. @app.post("/token", response_model=Token)
  114. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  115. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  116. if not user:
  117. raise HTTPException(status_code=400, detail="Incorrect username or password")
  118. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  119. access_token = create_access_token(
  120. data={"sub": user.username, "scopes": form_data.scopes},
  121. expires_delta=access_token_expires,
  122. )
  123. return {"access_token": access_token, "token_type": "bearer"}
  124. @app.get("/users/me/", response_model=User)
  125. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  126. return current_user
  127. @app.get("/users/me/items/")
  128. async def read_own_items(
  129. current_user: User = Security(get_current_active_user, scopes=["items"])
  130. ):
  131. return [{"item_id": "Foo", "owner": current_user.username}]
  132. @app.get("/status/")
  133. async def read_system_status(current_user: User = Depends(get_current_user)):
  134. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

  1. from datetime import datetime, timedelta
  2. from typing import List, Union
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: Union[str, None] = None
  38. scopes: List[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: Union[str, None] = None
  42. full_name: Union[str, None] = None
  43. disabled: Union[bool, None] = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: User = Security(get_current_user, scopes=["me"])
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
  116. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  117. if not user:
  118. raise HTTPException(status_code=400, detail="Incorrect username or password")
  119. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  120. access_token = create_access_token(
  121. data={"sub": user.username, "scopes": form_data.scopes},
  122. expires_delta=access_token_expires,
  123. )
  124. return {"access_token": access_token, "token_type": "bearer"}
  125. @app.get("/users/me/", response_model=User)
  126. async def read_users_me(current_user: User = Depends(get_current_active_user)):
  127. return current_user
  128. @app.get("/users/me/items/")
  129. async def read_own_items(
  130. current_user: User = Security(get_current_active_user, scopes=["items"])
  131. ):
  132. return [{"item_id": "Foo", "owner": current_user.username}]
  133. @app.get("/status/")
  134. async def read_system_status(current_user: User = Depends(get_current_user)):
  135. return {"status": "ok"}

Use the scopes

The parameter security_scopes will be of type SecurityScopes.

It will have a property scopes with a list containing all the scopes required by itself and all the dependencies that use this as a sub-dependency. That means, all the “dependants”… this might sound confusing, it is explained again later below.

The security_scopes object (of class SecurityScopes) also provides a scope_str attribute with a single string, containing those scopes separated by spaces (we are going to use it).

We create an HTTPException that we can re-use (raise) later at several points.

In this exception, we include the scopes required (if any) as a string separated by spaces (using scope_str). We put that string containing the scopes in the WWW-Authenticate header (this is part of the spec).

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

  1. from datetime import datetime, timedelta
  2. from typing import Annotated
  3. from fastapi import Depends, FastAPI, HTTPException, Security, status
  4. from fastapi.security import (
  5. OAuth2PasswordBearer,
  6. OAuth2PasswordRequestForm,
  7. SecurityScopes,
  8. )
  9. from jose import JWTError, jwt
  10. from passlib.context import CryptContext
  11. from pydantic import BaseModel, ValidationError
  12. # to get a string like this run:
  13. # openssl rand -hex 32
  14. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  15. ALGORITHM = "HS256"
  16. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  17. fake_users_db = {
  18. "johndoe": {
  19. "username": "johndoe",
  20. "full_name": "John Doe",
  21. "email": "johndoe@example.com",
  22. "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
  23. "disabled": False,
  24. },
  25. "alice": {
  26. "username": "alice",
  27. "full_name": "Alice Chains",
  28. "email": "alicechains@example.com",
  29. "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
  30. "disabled": True,
  31. },
  32. }
  33. class Token(BaseModel):
  34. access_token: str
  35. token_type: str
  36. class TokenData(BaseModel):
  37. username: str | None = None
  38. scopes: list[str] = []
  39. class User(BaseModel):
  40. username: str
  41. email: str | None = None
  42. full_name: str | None = None
  43. disabled: bool | None = None
  44. class UserInDB(User):
  45. hashed_password: str
  46. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  47. oauth2_scheme = OAuth2PasswordBearer(
  48. tokenUrl="token",
  49. scopes={"me": "Read information about the current user.", "items": "Read items."},
  50. )
  51. app = FastAPI()
  52. def verify_password(plain_password, hashed_password):
  53. return pwd_context.verify(plain_password, hashed_password)
  54. def get_password_hash(password):
  55. return pwd_context.hash(password)
  56. def get_user(db, username: str):
  57. if username in db:
  58. user_dict = db[username]
  59. return UserInDB(**user_dict)
  60. def authenticate_user(fake_db, username: str, password: str):
  61. user = get_user(fake_db, username)
  62. if not user:
  63. return False
  64. if not verify_password(password, user.hashed_password):
  65. return False
  66. return user
  67. def create_access_token(data: dict, expires_delta: timedelta | None = None):
  68. to_encode = data.copy()
  69. if expires_delta:
  70. expire = datetime.utcnow() + expires_delta
  71. else:
  72. expire = datetime.utcnow() + timedelta(minutes=15)
  73. to_encode.update({"exp": expire})
  74. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  75. return encoded_jwt
  76. async def get_current_user(
  77. security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
  78. ):
  79. if security_scopes.scopes:
  80. authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
  81. else:
  82. authenticate_value = "Bearer"
  83. credentials_exception = HTTPException(
  84. status_code=status.HTTP_401_UNAUTHORIZED,
  85. detail="Could not validate credentials",
  86. headers={"WWW-Authenticate": authenticate_value},
  87. )
  88. try:
  89. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  90. username: str = payload.get("sub")
  91. if username is None:
  92. raise credentials_exception
  93. token_scopes = payload.get("scopes", [])
  94. token_data = TokenData(scopes=token_scopes, username=username)
  95. except (JWTError, ValidationError):
  96. raise credentials_exception
  97. user = get_user(fake_users_db, username=token_data.username)
  98. if user is None:
  99. raise credentials_exception
  100. for scope in security_scopes.scopes:
  101. if scope not in token_data.scopes:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Not enough permissions",
  105. headers={"WWW-Authenticate": authenticate_value},
  106. )
  107. return user
  108. async def get_current_active_user(
  109. current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
  110. ):
  111. if current_user.disabled:
  112. raise HTTPException(status_code=400, detail="Inactive user")
  113. return current_user
  114. @app.post("/token", response_model=Token)
  115. async def login_for_access_token(
  116. form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
  117. ):
  118. user = authenticate_user(fake_users_db, form_data.username, form_data.password)
  119. if not user:
  120. raise HTTPException(status_code=400, detail="Incorrect username or password")
  121. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  122. access_token = create_access_token(
  123. data={"sub": user.username, "scopes": form_data.scopes},
  124. expires_delta=access_token_expires,
  125. )
  126. return {"access_token": access_token, "token_type": "bearer"}
  127. @app.get("/users/me/", response_model=User)
  128. async def read_users_me(
  129. current_user: Annotated[User, Depends(get_current_active_user)]
  130. ):
  131. return current_user
  132. @app.get("/users/me/items/")
  133. async def read_own_items(
  134. current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
  135. ):
  136. return [{"item_id": "Foo", "owner": current_user.username}]
  137. @app.get("/status/")
  138. async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
  139. return {"status": "ok"}
from datetime import datetime, timedelta
from typing import Annotated, List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}
from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError
from typing_extensions import Annotated

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None
    scopes: list[str] = []


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


class UserInDB(User):
    hashed_password: str


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: list[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Verify the username and data shape

We verify that we get a username, and extract the scopes.

And then we validate that data with the Pydantic model (catching the ValidationError exception), and if we get an error reading the JWT token or validating the data with Pydantic, we raise the HTTPException we created before.

For that, we update the Pydantic model TokenData with a new property scopes.

By validating the data with Pydantic we can make sure that we have, for example, exactly a list of str with the scopes and a str with the username.

Instead of, for example, a dict, or something else, as it could break the application at some point later, making it a security risk.

We also verify that we have a user with that username, and if not, we raise that same exception we created before.

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

from datetime import datetime, timedelta
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None
    scopes: list[str] = []


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


class UserInDB(User):
    hashed_password: str


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}
from datetime import datetime, timedelta
from typing import Annotated, List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}
from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError
from typing_extensions import Annotated

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None
    scopes: list[str] = []


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


class UserInDB(User):
    hashed_password: str


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: list[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Verify the scopes

We now verify that all the scopes required, by this dependency and all the dependants (including path operations), are included in the scopes provided in the token received, otherwise raise an HTTPException.

For this, we use security_scopes.scopes, that contains a list with all these scopes as str.

Python 3.10+Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.9+ non-AnnotatedPython 3.6+ non-Annotated

from datetime import datetime, timedelta
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None
    scopes: list[str] = []


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


class UserInDB(User):
    hashed_password: str


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}
from datetime import datetime, timedelta
from typing import Annotated, List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}
from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError
from typing_extensions import Annotated

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: Annotated[User, Security(get_current_user, scopes=["me"])]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=User)
async def read_users_me(
    current_user: Annotated[User, Depends(get_current_active_user)]
):
    return current_user


@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]


@app.get("/status/")
async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]):
    return {"status": "ok"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: str | None = None
    scopes: list[str] = []


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


class UserInDB(User):
    hashed_password: str


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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: timedelta | None = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: list[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Tip

Prefer to use the Annotated version if possible.

from datetime import datetime, timedelta
from typing import List, Union

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, ValidationError

# 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": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Chains",
        "email": "alicechains@example.com",
        "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm",
        "disabled": True,
    },
}


class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None
    scopes: List[str] = []


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


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"me": "Read information about the current user.", "items": "Read items."},
)

app = FastAPI()


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.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.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + 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(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)
):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
        token_data = TokenData(scopes=token_scopes, username=username)
    except (JWTError, ValidationError):
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_data.scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return user


async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username, "scopes": form_data.scopes},
        expires_delta=access_token_expires,
    )
    return {"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 = Security(get_current_active_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"}

Dependency tree and scopes

Let’s review again this dependency tree and the scopes.

As the get_current_active_user dependency has as a sub-dependency on get_current_user, the scope "me" declared at get_current_active_user will be included in the list of required scopes in the security_scopes.scopes passed to get_current_user.

The path operation itself also declares a scope, "items", so this will also be in the list of security_scopes.scopes passed to get_current_user.

Here’s how the hierarchy of dependencies and scopes looks like:

  • The path operation read_own_items has:
    • Required scopes ["items"] with the dependency:
    • get_current_active_user:
      • The dependency function get_current_active_user has:
        • Required scopes ["me"] with the dependency:
        • get_current_user:
          • The dependency function get_current_user has:
            • No scopes required by itself.
            • A dependency using oauth2_scheme.
            • A security_scopes parameter of type SecurityScopes:
              • This security_scopes parameter has a property scopes with a list containing all these scopes declared above, so:
                • security_scopes.scopes will contain ["me", "items"] for the path operation read_own_items.
                • security_scopes.scopes will contain ["me"] for the path operation read_users_me, because it is declared in the dependency get_current_active_user.
                • security_scopes.scopes will contain [] (nothing) for the path operation read_system_status, because it didn’t declare any Security with scopes, and its dependency, get_current_user, doesn’t declare any scope either.

Tip

The important and “magic” thing here is that get_current_user will have a different list of scopes to check for each path operation.

All depending on the scopes declared in each path operation and each dependency in the dependency tree for that specific path operation.

More details about SecurityScopes

You can use SecurityScopes at any point, and in multiple places, it doesn’t have to be at the “root” dependency.

It will always have the security scopes declared in the current Security dependencies and all the dependants for that specific path operation and that specific dependency tree.

Because the SecurityScopes will have all the scopes declared by dependants, you can use it to verify that a token has the required scopes in a central dependency function, and then declare different scope requirements in different path operations.

They will be checked independently for each path operation.

Check it

If you open the API docs, you can authenticate and specify which scopes you want to authorize.

OAuth2 scopes - 图2

If you don’t select any scope, you will be “authenticated”, but when you try to access /users/me/ or /users/me/items/ you will get an error saying that you don’t have enough permissions. You will still be able to access /status/.

And if you select the scope me but not the scope items, you will be able to access /users/me/ but not /users/me/items/.

That’s what would happen to a third party application that tried to access one of these path operations with a token provided by a user, depending on how many permissions the user gave the application.

About third party integrations

In this example we are using the OAuth2 “password” flow.

This is appropriate when we are logging in to our own application, probably with our own frontend.

Because we can trust it to receive the username and password, as we control it.

But if you are building an OAuth2 application that others would connect to (i.e., if you are building an authentication provider equivalent to Facebook, Google, GitHub, etc.) you should use one of the other flows.

The most common is the implicit flow.

The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.

Note

It’s common that each authentication provider names their flows in a different way, to make it part of their brand.

But in the end, they are implementing the same OAuth2 standard.

FastAPI includes utilities for all these OAuth2 authentication flows in fastapi.security.oauth2.

Security in decorator dependencies

The same way you can define a list of Depends in the decorator’s dependencies parameter (as explained in Dependencies in path operation decorators), you could also use Security with scopes there.