I`m using Auth0 authentification in a webapp / django-server combination. Auth0 is not the fastest auth framework, it always takes 200ms to authenticate. My webapp sends a lot of requests to the django server, so I thought about caching the authentication for a few seconds. This improves the speed of my app a lot.
Is this a good way? Do you see any disadvantages / security issues in doing it this way?
django config:
REST_FRAMEWORK = {
(...)
'DEFAULT_AUTHENTICATION_CLASSES': (
(...)
'rg_auth.rest_framework_authentication_classes.RgJSONWebTokenAuthentication',
(...)
),
(...)
}
authentication class:
import hashlib
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import get_authorization_header
from django.core.cache import cache
class RgJSONWebTokenAuthentication(JSONWebTokenAuthentication):
def authenticate(self, request):
# Get from cache
cache_key = self._rg_get_cache_key(request)
cached_user_payload_tuple = cache.get(cache_key)
# Is cache set?
if cached_user_payload_tuple:
# Cache is set: Return user/payload tuple
return cached_user_payload_tuple
else:
# Cache is not set: Authenticate and save tuple to cache for 10 seconds
user_payload_tuple = super().authenticate(request)
if user_payload_tuple:
# Set cache
cache.set(cache_key, user_payload_tuple, 10)
# Return tuple
return user_payload_tuple
def _rg_get_cache_key(self, request):
auth_header = get_authorization_header(request)
auth_header_md5 = hashlib.md5(auth_header).hexdigest()
return "RgJSONWebTokenAuthentication_{}".format(auth_header_md5)