cloud authentication ai_generated true

Azure AD token works for wrong tenant or returns 'AADSTS50020: User account does not exist in tenant'

ID: cloud/azure-ad-token-cache-cross-tenant

Also available as: JSON · Markdown
82%Fix Rate
85%Confidence
3Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
any active

Root Cause

MSAL token cache uses authority URL as part of the cache key. If you create multiple ConfidentialClientApplication instances with different tenants but share the same cache, tokens leak across tenants.

generic

Workarounds

  1. 95% success Use separate token caches per tenant (partition by tenant_id)
    cache = msal.SerializableTokenCache(); app = msal.ConfidentialClientApplication(client_id, authority=f'https://login.microsoftonline.com/{tenant_id}', token_cache=cache)
  2. 90% success Use MSAL's built-in cache partitioning with partition_key
    app.acquire_token_for_client(scopes, claims_challenge=None, data={'partition_key': tenant_id})

Dead Ends

Common approaches that don't work:

  1. Use a single shared MSAL token cache for all tenants 88% fail

    Tokens from tenant A may be served for tenant B requests. The cache key includes authority but bugs in cache partitioning cause cross-tenant leaks.

  2. Create a new ConfidentialClientApplication per request 72% fail

    Bypasses caching entirely. Every request does a full token acquisition, adding 200-500ms latency.