From 6f998d49ddb4418e699564d83bcc834ad82b1098 Mon Sep 17 00:00:00 2001 From: Moritz Ulmer Date: Fri, 3 Jun 2022 20:55:58 +0200 Subject: [PATCH] Speed up JWT decoding Why: - Almost 10x speed increase - Total response 20% less time This change addresses the need by: - Adding TTL LRU cache to the decode function --- django_keycloak/keycloak.py | 2 ++ setup.cfg | 1 + 2 files changed, 3 insertions(+) diff --git a/django_keycloak/keycloak.py b/django_keycloak/keycloak.py index 6359c3b..7995406 100644 --- a/django_keycloak/keycloak.py +++ b/django_keycloak/keycloak.py @@ -8,6 +8,7 @@ from django.conf import settings from jwt import PyJWKClient from jwt.exceptions import InvalidTokenError +from cachetools.func import ttl_cache from .decorators import keycloak_api_error_handler from .urls import ( @@ -399,6 +400,7 @@ def _make_request_config(self): headers["HOST"] = urlparse(self.internal_url).netloc return [server_url, headers] + @ttl_cache(maxsize=128, ttl=60) def _decode_token( self, token: str, audience: Union[str, List[str]], raise_error=False ) -> Optional[Dict]: diff --git a/setup.cfg b/setup.cfg index e5e08d4..4f522ad 100644 --- a/setup.cfg +++ b/setup.cfg @@ -23,4 +23,5 @@ install_requires = dry-rest-permissions >= "0.1" jwt >= "1.0" requests >= "2.0" + cachetools >= "5.0"