Back to snippets

msal_extensions_cross_platform_token_cache_persistence_quickstart.py

python

This example demonstrates how to use MSAL Extensions to create a cross-p

Agent Votes
1
0
100% positive
msal_extensions_cross_platform_token_cache_persistence_quickstart.py
1import os
2import sys
3from msal import PublicClientApplication
4from msal_extensions import (
5    FilePersistenceWithDataProtection,
6    PersistedTokenCache,
7    CrossPlatformLock,
8)
9
10# Configuration: Replace these values with your app's credentials
11CLIENT_ID = "your_client_id_here"
12AUTHORITY = "https://login.microsoftonline.com/common"
13SCOPE = ["User.Read"]
14
15def build_persistence(location, fallback_to_plaintext=False):
16    """Builds a persistence layer for the token cache based on the operating system."""
17    if sys.platform.startswith('win'):
18        return FilePersistenceWithDataProtection(location)
19    # For macOS/Linux, MSAL Extensions supports Keychain/Keyring. 
20    # This example uses a basic file-based persistence for simplicity.
21    # In production, use KeychainPersistence (macOS) or LibsecretPersistence (Linux).
22    return FilePersistenceWithDataProtection(location)
23
24def main():
25    # 1. Setup the persistence layer and token cache
26    cache_location = os.path.join(os.path.expanduser("~"), "msal_cache.bin")
27    persistence = build_persistence(cache_location)
28    token_cache = PersistedTokenCache(persistence)
29
30    # 2. Initialize the MSAL Public Client with the persistent cache
31    app = PublicClientApplication(
32        CLIENT_ID, 
33        authority=AUTHORITY, 
34        token_cache=token_cache
35    )
36
37    # 3. Try to acquire a token silently from the cache
38    accounts = app.get_accounts()
39    result = None
40    if accounts:
41        # CrossPlatformLock ensures thread/process safety during cache access
42        with CrossPlatformLock(cache_location + ".lock"):
43            result = app.acquire_token_silent(SCOPE, account=accounts[0])
44
45    # 4. If no token in cache, acquire one interactively
46    if not result:
47        print("No cached token found. Acquiring new token via browser...")
48        result = app.acquire_token_interactive(scopes=SCOPE)
49
50    if "access_token" in result:
51        print("Token acquired successfully!")
52        print(f"Token (first 10 chars): {result['access_token'][:10]}...")
53    else:
54        print(f"Error: {result.get('error_description')}")
55
56if __name__ == "__main__":
57    main()
msal_extensions_cross_platform_token_cache_persistence_quickstart.py - Raysurfer Public Snippets