Open
Description
I was wondering if there is a use for supporting Reis as a Cache?
I've seen some samples from the node-version of Microsoft Authentication Library MSAL.
It appears to me, that it might be straight forward, implementing a similar adapter based on the class BasePersistence of the python extensions for MSAL from this library. Something like that:
import redis
import json
from msal import ConfidentialClientApplication
from msal_extensions.token_cache import PersistedTokenCache
from msal_extensions.persistence import BasePersistence
from datetime import datetime, timedelta
# Redis connection:
redis_client = redis.Redis(
host=<redis-host>,
port=<redis-port>,
password=<redis-password>
)
class RedisPersistence(BasePersistence):
"""Redis persistence class for the token cache"""
def __init__(self, user_account):
self.user_account = user_account
def save(self, content):
"""Saves the token to the cache"""
result = redis_client.json().set(self.get_location(), ".", content)
return json.dumps(result)
def load(self):
"""Loads the token from the cache"""
result = redis_client.json().get(self.get_location())
return json.dumps(result)
def get_location(self):
"""Returns the location in the cache"""
location = f"msal:{self.user_account['homeAccountId']}"
return location
def time_last_modified(self):
"""Returns the time the cache was last accessed"""
try:
idle_time = redis_client.object("idletime", self.get_location())
if idle_time:
last_accessed_time = datetime.now() - timedelta(seconds=idle_time)
return last_accessed_time.timestamp()
except Exception:
raise Exception("no modification time available")
# Instantiate the cache:
def get_persistent_cache(user_account):
"""Returns the persistent cache for the user account"""
persistence = RedisPersistence(user_account)
persistedTokenCache = PersistedTokenCache(persistence)
return persistedTokenCache
# use microsoft Authentication Library with Redis for a specific user_account,
# coming from the authentication stage:
cache = get_persistent_cache(user_account)
msal_client = ConfidentialClientApplication(
client_id=<client-id>,
client_credential=<client-secret>,
authority=<authority>,
token_cache=cache,
)
accounts = msal_client.get_accounts(user_account["username"])
for account in accounts:
result = msal_conf_client.acquire_token_silent([<scopes>], account=account)
if "access_token" in result:
return result["access_token"]