Skip to content

Commit

Permalink
Implement JWT expiration check (GH-43)
Browse files Browse the repository at this point in the history
Co-authored-by: Ilya Borowski <[email protected]>
  • Loading branch information
ArtyomVancyan and Scurrra authored Jul 21, 2024
2 parents d22bb4e + fc60e7d commit 1e6d30a
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/fastapi_oauth2/middleware.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from typing import Any
from typing import Awaitable
from typing import Callable
Expand Down Expand Up @@ -27,6 +28,7 @@
from .claims import Claims
from .config import OAuth2Config
from .core import OAuth2Core
from .exceptions import OAuth2AuthenticationError


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

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


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

user = User(Auth.jwt_decode(param))
token_data = Auth.jwt_decode(param)
if token_data["exp"] and token_data["exp"] < int(datetime.now(timezone.utc).timestamp()):
raise OAuth2AuthenticationError(401, "Token expired")

user = User(token_data)
auth = Auth(user.pop("scope", []))
auth.provider = auth.clients.get(user.get("provider"))
claims = auth.provider.claims if auth.provider else {}
Expand Down

0 comments on commit 1e6d30a

Please sign in to comment.