Skip to content

Commit 1e6d30a

Browse files
Implement JWT expiration check (GH-43)
Co-authored-by: Ilya Borowski <40835268+Scurrra@users.noreply.github.com>
2 parents d22bb4e + fc60e7d commit 1e6d30a

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/fastapi_oauth2/middleware.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from datetime import datetime
22
from datetime import timedelta
3+
from datetime import timezone
34
from typing import Any
45
from typing import Awaitable
56
from typing import Callable
@@ -27,6 +28,7 @@
2728
from .claims import Claims
2829
from .config import OAuth2Config
2930
from .core import OAuth2Core
31+
from .exceptions import OAuth2AuthenticationError
3032

3133

3234
class Auth(AuthCredentials):
@@ -51,7 +53,7 @@ def jwt_decode(cls, token: str) -> dict:
5153

5254
@classmethod
5355
def jwt_create(cls, token_data: dict) -> str:
54-
expire = datetime.utcnow() + timedelta(seconds=cls.expires)
56+
expire = datetime.now(timezone.utc) + timedelta(seconds=cls.expires)
5557
return cls.jwt_encode({**token_data, "exp": expire})
5658

5759

@@ -106,7 +108,11 @@ async def authenticate(self, request: Request) -> Optional[Tuple[Auth, User]]:
106108
if not scheme or not param:
107109
return Auth(), User()
108110

109-
user = User(Auth.jwt_decode(param))
111+
token_data = Auth.jwt_decode(param)
112+
if token_data["exp"] and token_data["exp"] < int(datetime.now(timezone.utc).timestamp()):
113+
raise OAuth2AuthenticationError(401, "Token expired")
114+
115+
user = User(token_data)
110116
auth = Auth(user.pop("scope", []))
111117
auth.provider = auth.clients.get(user.get("provider"))
112118
claims = auth.provider.claims if auth.provider else {}

0 commit comments

Comments
 (0)