diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 7ee8d83b6..7f65072f6 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -667,7 +667,7 @@ class OAuth2ClientCredentials(OAuth2): ), ], scheme_name: Annotated[ - Optional[str], + str | None, Doc( """ Security scheme name. @@ -677,7 +677,7 @@ class OAuth2ClientCredentials(OAuth2): ), ] = None, scopes: Annotated[ - Optional[Dict[str, str]], + dict[str, str] | None, Doc( """ The OAuth2 scopes that would be required by the *path operations* that @@ -686,7 +686,7 @@ class OAuth2ClientCredentials(OAuth2): ), ] = None, description: Annotated[ - Optional[str], + str | None, Doc( """ Security scheme description. @@ -734,16 +734,12 @@ class OAuth2ClientCredentials(OAuth2): auto_error=auto_error, ) - async def __call__(self, request: Request) -> Optional[str]: + async def __call__(self, request: Request) -> str | None: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: - raise HTTPException( - status_code=HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}, - ) + raise self.make_not_authenticated_error() else: return None return param diff --git a/tests/test_security_oauth2_client_credentials.py b/tests/test_security_oauth2_client_credentials.py index d23a5bc18..1cfc9525c 100644 --- a/tests/test_security_oauth2_client_credentials.py +++ b/tests/test_security_oauth2_client_credentials.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Annotated from fastapi import FastAPI, Security from fastapi.security import OAuth2ClientCredentials @@ -10,7 +10,7 @@ oauth2_scheme = OAuth2ClientCredentials(tokenUrl="token", auto_error=True) @app.get("/items/") -async def read_items(token: Optional[str] = Security(oauth2_scheme)): +async def read_items(token: Annotated[str, Security(oauth2_scheme)]): return {"token": token} diff --git a/tests/test_security_oauth2_client_credentials_optional.py b/tests/test_security_oauth2_client_credentials_optional.py index f281a61a3..8a748bf1b 100644 --- a/tests/test_security_oauth2_client_credentials_optional.py +++ b/tests/test_security_oauth2_client_credentials_optional.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Annotated from fastapi import FastAPI, Security from fastapi.security import OAuth2ClientCredentials @@ -10,7 +10,7 @@ oauth2_scheme = OAuth2ClientCredentials(tokenUrl="token", auto_error=False) @app.get("/items/") -async def read_items(token: Optional[str] = Security(oauth2_scheme)): +async def read_items(token: Annotated[str | None, Security(oauth2_scheme)]): return {"token": token}