Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/msal/token_cache.py: 27%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

199 statements  

1import base64 

2import hashlib 

3import json 

4import threading 

5import time 

6import logging 

7import warnings 

8 

9from .authority import canonicalize 

10from .oauth2cli.oidc import decode_part, _decode_id_token_claims 

11from .oauth2cli.oauth2 import Client 

12 

13 

14logger = logging.getLogger(__name__) 

15_GRANT_TYPE_BROKER = "broker" 

16 

17# Fields in the request data dict that should NOT be included in the extended 

18# cache key hash. Everything else in data IS included, because those are extra 

19# body parameters going on the wire and must differentiate cached tokens. 

20# 

21# Excluded fields and reasons: 

22# - "client_id" : Standard OAuth2 client identifier, same for every request 

23# - "grant_type" : It is possible to combine grants to get tokens, e.g. obo + refresh_token, auth_code + refresh_token etc. 

24# - "scope" : Already represented as "target" in the AT cache key 

25# - "claims" : Handled separately; its presence forces a token refresh 

26# - "username" : Standard ROPC grant parameter. Tokens are cached by user ID (subject or oid+tid) instead 

27# - "password" : Standard ROPC grant parameter. Tokens are tied to credentials. 

28# - "refresh_token" : Standard refresh grant parameter 

29# - "code" : Standard authorization code grant parameter 

30# - "redirect_uri" : Standard authorization code grant parameter 

31# - "code_verifier" : Standard PKCE parameter 

32# - "device_code" : Standard device flow parameter 

33# - "assertion" : Standard OBO/SAML assertion (RFC 7521) 

34# - "requested_token_use" : OBO indicator ("on_behalf_of"), not an extra param 

35# - "client_assertion" : Client authentication credential (RFC 7521 §4.2) 

36# - "client_assertion_type" : Client authentication type (RFC 7521 §4.2) 

37# - "client_secret" : Client authentication secret 

38# - "token_type" : Used for SSH-cert/POP detection; AT entry stores separately 

39# - "req_cnf" : Ephemeral proof-of-possession nonce, changes per request 

40# - "key_id" : Already handled as a separate cache lookup field 

41# 

42# Included fields (examples — anything NOT in this set is included): 

43# - "fmi_path" : Federated Managed Identity credential path 

44# - any future non-standard body parameter that should isolate cache entries 

45_EXT_CACHE_KEY_EXCLUDED_FIELDS = frozenset({ 

46 # Standard OAuth2 body parameters — these appear in every token request 

47 # and must NOT influence the extended cache key. 

48 # Only non-standard fields (e.g. fmi_path) should contribute to the hash. 

49 "client_id", 

50 "grant_type", 

51 "scope", 

52 "claims", 

53 "username", 

54 "password", 

55 "refresh_token", 

56 "code", 

57 "redirect_uri", 

58 "code_verifier", 

59 "device_code", 

60 "assertion", 

61 "requested_token_use", 

62 "client_assertion", 

63 "client_assertion_type", 

64 "client_secret", 

65 "token_type", 

66 "req_cnf", 

67 "key_id", 

68 # user_fic grant parameters — these are standard body params for the 

69 # user_fic flow; FIC tokens use normal user cache keys (not extended). 

70 "user_federated_identity_credential", 

71 "user_id", 

72 "client_info", 

73}) 

74 

75 

76def _compute_ext_cache_key(data): 

77 """Compute an extended cache key hash from extra body parameters in *data*. 

78 

79 All fields in *data* that go on the wire are included in the hash, 

80 EXCEPT those listed in ``_EXT_CACHE_KEY_EXCLUDED_FIELDS``. 

81 This ensures tokens acquired with different parameter values 

82 (e.g., different FMI paths) are cached separately. 

83 

84 The hash may also intentionally include cache-key-only pseudo-parameters 

85 such as ``client_claims`` -- these are stripped from the wire body by the 

86 oauth2 layer but are retained in *data* precisely so that different 

87 client-originated claims route to separate cache entries. 

88 

89 Returns an empty string when *data* has no hashable fields. 

90 

91 The algorithm matches MSAL .NET's ``ComputeAccessTokenExtCacheKey``: sorted 

92 key+value pairs are concatenated (no separators) and SHA256 hashed, then 

93 base64url encoded. This keeps the hash byte-identical to MSAL .NET. 

94 

95 MSAL Go's ``CacheExtKeyGenerator`` has since switched to a length-prefixed 

96 encoding (AzureAD/microsoft-authentication-library-for-go#629) to make it 

97 injective; Python deliberately tracks .NET instead, so these hashes are not 

98 byte-identical to current Go. Caches are not shared across languages, so the 

99 difference does not affect runtime correctness. 

100 """ 

101 if not data: 

102 return "" 

103 cache_components = { 

104 k: str(v) for k, v in data.items() 

105 if k not in _EXT_CACHE_KEY_EXCLUDED_FIELDS and v 

106 } 

107 if not cache_components: 

108 return "" 

109 # Sort keys, then concatenate key+value pairs with no separators. This 

110 # matches MSAL .NET's ComputeAccessTokenExtCacheKey byte-for-byte. (See the 

111 # docstring re: the Go #629 length-prefixed divergence.) 

112 key_str = "".join( 

113 k + cache_components[k] for k in sorted(cache_components.keys()) 

114 ) 

115 hash_bytes = hashlib.sha256(key_str.encode("utf-8")).digest() 

116 return base64.urlsafe_b64encode(hash_bytes).rstrip(b"=").decode("ascii").lower() 

117 

118 

119def _parse_claims_or_raise(claims): 

120 """Parse a claims JSON string into a dict, or raise a friendly ``ValueError``. 

121 

122 The raw claims value is never included in the error message because it may 

123 contain sensitive data. Mirrors MSAL .NET's ``ClaimsHelper.ParseClaimsOrThrow``. 

124 """ 

125 try: 

126 parsed = json.loads(claims) 

127 except (ValueError, TypeError) as ex: 

128 # json.JSONDecodeError (malformed JSON) is a subclass of ValueError; 

129 # TypeError is raised when *claims* is not a str/bytes/bytearray. Both 

130 # are surfaced as the same friendly ValueError so every caller behaves 

131 # consistently regardless of the bad input's type. 

132 raise ValueError( 

133 "The claims value is not valid JSON. " 

134 "See https://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter." 

135 ) from ex 

136 if not isinstance(parsed, dict): 

137 # A valid JSON array, scalar, or the literal "null" is not a claims object. 

138 raise ValueError( 

139 "The claims value is not a valid JSON object. " 

140 "See https://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter.") 

141 return parsed 

142 

143 

144def _deep_merge_dict(base, overlay): 

145 """Recursively merge ``overlay`` into ``base``, returning a new dict. 

146 

147 Nested dicts are merged; for any other value type, ``overlay`` wins. 

148 """ 

149 result = dict(base) 

150 for key, value in overlay.items(): 

151 if (key in result 

152 and isinstance(result[key], dict) and isinstance(value, dict)): 

153 result[key] = _deep_merge_dict(result[key], value) 

154 else: 

155 result[key] = value 

156 return result 

157 

158 

159def _merge_claims(claims_a, claims_b): 

160 """Merge two claims JSON strings into a single JSON string. 

161 

162 If either side is empty/None, the other is returned as-is. Mirrors MSAL 

163 .NET's ``ClaimsHelper.MergeClaimsObjects``. 

164 """ 

165 if not claims_a: 

166 return claims_b 

167 if not claims_b: 

168 return claims_a 

169 merged = _deep_merge_dict( 

170 _parse_claims_or_raise(claims_a), _parse_claims_or_raise(claims_b)) 

171 return json.dumps(merged) 

172 

173 

174def is_subdict_of(small, big): 

175 return dict(big, **small) == big 

176 

177def _get_username(id_token_claims): 

178 return id_token_claims.get( 

179 "preferred_username", # AAD 

180 id_token_claims.get("upn")) # ADFS 2019 

181 

182class TokenCache(object): 

183 """This is considered as a base class containing minimal cache behavior. 

184 

185 Although it maintains tokens using unified schema across all MSAL libraries, 

186 this class does not serialize/persist them. 

187 See subclass :class:`SerializableTokenCache` for details on serialization. 

188 """ 

189 

190 class CredentialType: 

191 ACCESS_TOKEN = "AccessToken" 

192 ACCESS_TOKEN_EXTENDED = "atext" # Used when ext_cache_key is present (matches Go/dotnet) 

193 REFRESH_TOKEN = "RefreshToken" 

194 ACCOUNT = "Account" # Not exactly a credential type, but we put it here 

195 ID_TOKEN = "IdToken" 

196 APP_METADATA = "AppMetadata" 

197 

198 class AuthorityType: 

199 ADFS = "ADFS" 

200 MSSTS = "MSSTS" # MSSTS means AAD v2 for both AAD & MSA 

201 

202 def __init__(self): 

203 self._lock = threading.RLock() 

204 self._cache = {} 

205 self.key_makers = { 

206 # Note: We have changed token key format before when ordering scopes; 

207 # changing token key won't result in cache miss. 

208 self.CredentialType.REFRESH_TOKEN: 

209 lambda home_account_id=None, environment=None, client_id=None, 

210 target=None, **ignored_payload_from_a_real_token: 

211 "-".join([ 

212 home_account_id or "", 

213 environment or "", 

214 self.CredentialType.REFRESH_TOKEN, 

215 client_id or "", 

216 "", # RT is cross-tenant in AAD 

217 target or "", # raw value could be None if deserialized from other SDK 

218 ]).lower(), 

219 self.CredentialType.ACCESS_TOKEN: 

220 lambda home_account_id=None, environment=None, client_id=None, 

221 realm=None, target=None, 

222 ext_cache_key=None, 

223 # Note: New field(s) can be added here 

224 #key_id=None, 

225 **ignored_payload_from_a_real_token: 

226 "-".join([ # Note: Could use a hash here to shorten key length 

227 home_account_id or "", 

228 environment or "", 

229 # Use "atext" credential type when ext_cache_key is 

230 # present, matching MSAL Go and MSAL .NET behaviour. 

231 "atext" if ext_cache_key else "AccessToken", 

232 client_id or "", 

233 realm or "", 

234 target or "", 

235 #key_id or "", # So ATs of different key_id can coexist 

236 ] + ([ext_cache_key] if ext_cache_key else []) 

237 ).lower(), 

238 self.CredentialType.ID_TOKEN: 

239 lambda home_account_id=None, environment=None, client_id=None, 

240 realm=None, **ignored_payload_from_a_real_token: 

241 "-".join([ 

242 home_account_id or "", 

243 environment or "", 

244 self.CredentialType.ID_TOKEN, 

245 client_id or "", 

246 realm or "", 

247 "" # Albeit irrelevant, schema requires an empty scope here 

248 ]).lower(), 

249 self.CredentialType.ACCOUNT: 

250 lambda home_account_id=None, environment=None, realm=None, 

251 **ignored_payload_from_a_real_entry: 

252 "-".join([ 

253 home_account_id or "", 

254 environment or "", 

255 realm or "", 

256 ]).lower(), 

257 self.CredentialType.APP_METADATA: 

258 lambda environment=None, client_id=None, **kwargs: 

259 "appmetadata-{}-{}".format(environment or "", client_id or ""), 

260 } 

261 

262 def _get_access_token( 

263 self, 

264 home_account_id, environment, client_id, realm, target, # Together they form a compound key 

265 ext_cache_key=None, 

266 default=None, 

267 ): # O(1) 

268 return self._get( 

269 self.CredentialType.ACCESS_TOKEN, 

270 self.key_makers[TokenCache.CredentialType.ACCESS_TOKEN]( 

271 home_account_id=home_account_id, 

272 environment=environment, 

273 client_id=client_id, 

274 realm=realm, 

275 target=" ".join(target), 

276 ext_cache_key=ext_cache_key, 

277 ), 

278 default=default) 

279 

280 def _get_app_metadata(self, environment, client_id, default=None): # O(1) 

281 return self._get( 

282 self.CredentialType.APP_METADATA, 

283 self.key_makers[TokenCache.CredentialType.APP_METADATA]( 

284 environment=environment, 

285 client_id=client_id, 

286 ), 

287 default=default) 

288 

289 def _get(self, credential_type, key, default=None): # O(1) 

290 with self._lock: 

291 return self._cache.get(credential_type, {}).get(key, default) 

292 

293 @staticmethod 

294 def _is_matching(entry: dict, query: dict, target_set: set = None) -> bool: 

295 query_with_lowercase_environment = { 

296 # __add() canonicalized entry's environment value to lower case, 

297 # so we do the same here. 

298 k: v.lower() if k == "environment" and isinstance(v, str) else v 

299 for k, v in query.items() 

300 } if query else {} 

301 return is_subdict_of(query_with_lowercase_environment, entry) and ( 

302 target_set <= set(entry.get("target", "").split()) 

303 if target_set else True) 

304 

305 def search(self, credential_type, target=None, query=None, *, now=None): # O(n) generator 

306 """Returns a generator of matching entries. 

307 

308 It is O(1) for AT hits, and O(n) for other types. 

309 Note that it holds a lock during the entire search. 

310 """ 

311 target = sorted(target or []) # Match the order sorted by add() 

312 assert isinstance(target, list), "Invalid parameter type" 

313 

314 preferred_result = None 

315 if (credential_type == self.CredentialType.ACCESS_TOKEN 

316 and isinstance(query, dict) 

317 and "home_account_id" in query and "environment" in query 

318 and "client_id" in query and "realm" in query and target 

319 ): # Special case for O(1) AT lookup 

320 preferred_result = self._get_access_token( 

321 query["home_account_id"], query["environment"], 

322 query["client_id"], query["realm"], target, 

323 ext_cache_key=query.get("ext_cache_key")) 

324 if preferred_result and self._is_matching( 

325 preferred_result, query, 

326 # Needs no target_set here because it is satisfied by dict key 

327 ): 

328 yield preferred_result 

329 

330 target_set = set(target) 

331 with self._lock: 

332 # O(n) search. The key is NOT used in search. 

333 now = int(time.time() if now is None else now) 

334 expired_access_tokens = [ 

335 # Especially when/if we key ATs by ephemeral fields such as key_id, 

336 # stale ATs keyed by an old key_id would stay forever. 

337 # Here we collect them for their removal. 

338 ] 

339 for entry in self._cache.get(credential_type, {}).values(): 

340 if ( # Automatically delete expired access tokens 

341 credential_type == self.CredentialType.ACCESS_TOKEN 

342 and int(entry["expires_on"]) < now 

343 ): 

344 expired_access_tokens.append(entry) # Can't delete them within current for-loop 

345 continue 

346 if (entry != preferred_result # Avoid yielding the same entry twice 

347 and self._is_matching(entry, query, target_set=target_set) 

348 ): 

349 # Cache isolation for extended cache keys (e.g., FMI path). 

350 # Entries with ext_cache_key must not match queries without one. 

351 if (credential_type == self.CredentialType.ACCESS_TOKEN 

352 and "ext_cache_key" in entry 

353 and "ext_cache_key" not in (query or {}) 

354 ): 

355 continue 

356 yield entry 

357 for at in expired_access_tokens: 

358 self.remove_at(at) 

359 

360 def find(self, credential_type, target=None, query=None, *, now=None): 

361 """Equivalent to list(search(...)).""" 

362 warnings.warn( 

363 "Use list(search(...)) instead to explicitly get a list.", 

364 DeprecationWarning) 

365 return list(self.search(credential_type, target=target, query=query, now=now)) 

366 

367 def add(self, event, now=None): 

368 """Handle a token obtaining event, and add tokens into cache.""" 

369 def make_clean_copy(dictionary, sensitive_fields): # Masks sensitive info 

370 return { 

371 k: "********" if k in sensitive_fields else v 

372 for k, v in dictionary.items() 

373 } 

374 clean_event = dict( 

375 event, 

376 data=make_clean_copy(event.get("data", {}), ( 

377 "password", "client_secret", "refresh_token", "assertion", 

378 "user_federated_identity_credential", 

379 # Client-originated claims may carry sensitive values; they are 

380 # kept in data only for ext_cache_key computation, so redact them 

381 # from the debug log (both the cache-key pseudo-param and the 

382 # merged wire parameter). 

383 "client_claims", "claims", 

384 )), 

385 response=make_clean_copy(event.get("response", {}), ( 

386 "id_token_claims", # Provided by broker 

387 "access_token", "refresh_token", "id_token", "username", 

388 )), 

389 ) 

390 logger.debug("event=%s", json.dumps( 

391 # We examined and concluded that this log won't have Log Injection risk, 

392 # because the event payload is already in JSON so CR/LF will be escaped. 

393 clean_event, 

394 indent=4, sort_keys=True, 

395 default=str, # assertion is in bytes in Python 3 

396 )) 

397 return self.__add(event, now=now) 

398 

399 def __parse_account(self, response, id_token_claims): 

400 """Return client_info and home_account_id""" 

401 if "client_info" in response: # It happens when client_info and profile are in request 

402 client_info = json.loads(decode_part(response["client_info"])) 

403 if "uid" in client_info and "utid" in client_info: 

404 return client_info, "{uid}.{utid}".format(**client_info) 

405 # https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/387 

406 if id_token_claims: # This would be an end user on ADFS-direct scenario 

407 sub = id_token_claims["sub"] # "sub" always exists, per OIDC specs 

408 return {"uid": sub}, sub 

409 # client_credentials flow will reach this code path 

410 return {}, None 

411 

412 def __add(self, event, now=None): 

413 # event typically contains: client_id, scope, token_endpoint, 

414 # response, params, data, grant_type 

415 environment = realm = None 

416 if "token_endpoint" in event: 

417 _, environment, realm = canonicalize(event["token_endpoint"]) 

418 if "environment" in event: # Always available unless in legacy test cases 

419 environment = event["environment"] # Set by application.py 

420 response = event.get("response", {}) 

421 data = event.get("data", {}) 

422 access_token = response.get("access_token") 

423 refresh_token = response.get("refresh_token") 

424 id_token = response.get("id_token") 

425 id_token_claims = response.get("id_token_claims") or ( # Prefer the claims from broker 

426 # MSAL does not validate the ID token; it only decodes the claims. 

427 # https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/911 

428 _decode_id_token_claims(id_token) if id_token else {}) 

429 client_info, home_account_id = self.__parse_account(response, id_token_claims) 

430 

431 target = ' '.join(sorted(event.get("scope") or [])) # Schema should have required sorting 

432 

433 with self._lock: 

434 now = int(time.time() if now is None else now) 

435 

436 if access_token: 

437 default_expires_in = ( # https://www.rfc-editor.org/rfc/rfc6749#section-5.1 

438 int(response.get("expires_on")) - now # Some Managed Identity emits this 

439 ) if response.get("expires_on") else 600 

440 expires_in = int( # AADv1-like endpoint returns a string 

441 response.get("expires_in", default_expires_in)) 

442 ext_expires_in = int( # AADv1-like endpoint returns a string 

443 response.get("ext_expires_in", expires_in)) 

444 at = { 

445 "credential_type": self.CredentialType.ACCESS_TOKEN, 

446 "secret": access_token, 

447 "home_account_id": home_account_id, 

448 "environment": environment, 

449 "client_id": event.get("client_id"), 

450 "target": target, 

451 "realm": realm, 

452 "token_type": response.get("token_type", "Bearer"), 

453 "cached_at": str(now), # Schema defines it as a string 

454 "expires_on": str(now + expires_in), # Same here 

455 "extended_expires_on": str(now + ext_expires_in) # Same here 

456 } 

457 at.update({k: data[k] for k in data if k in { 

458 # Also store extra data which we explicitly allow 

459 # So that we won't accidentally store a user's password etc. 

460 "key_id", # It happens in SSH-cert or POP scenario 

461 }}) 

462 # Compute and store extended cache key for cache isolation 

463 # (e.g., different FMI paths should have separate cache entries) 

464 ext_cache_key = _compute_ext_cache_key(data) 

465 

466 if ext_cache_key: 

467 at["ext_cache_key"] = ext_cache_key 

468 if "refresh_in" in response: 

469 refresh_in = response["refresh_in"] # It is an integer 

470 at["refresh_on"] = str(now + refresh_in) # Schema wants a string 

471 self.modify(self.CredentialType.ACCESS_TOKEN, at, at) 

472 

473 if client_info and not event.get("skip_account_creation"): 

474 account = { 

475 "home_account_id": home_account_id, 

476 "environment": environment, 

477 "realm": realm, 

478 "local_account_id": event.get( 

479 "_account_id", # Came from mid-tier code path. 

480 # Emperically, it is the oid in AAD or cid in MSA. 

481 id_token_claims.get("oid", id_token_claims.get("sub"))), 

482 "username": _get_username(id_token_claims) 

483 or data.get("username") # Falls back to ROPC username 

484 or event.get("username") # Falls back to Federated ROPC username 

485 or "", # The schema does not like null 

486 "authority_type": event.get( 

487 "authority_type", # Honor caller's choice of authority_type 

488 self.AuthorityType.ADFS if realm == "adfs" 

489 else self.AuthorityType.MSSTS), 

490 # "client_info": response.get("client_info"), # Optional 

491 } 

492 grant_types_that_establish_an_account = ( 

493 _GRANT_TYPE_BROKER, "authorization_code", "password", 

494 Client.DEVICE_FLOW["GRANT_TYPE"], "user_fic") 

495 if event.get("grant_type") in grant_types_that_establish_an_account: 

496 account["account_source"] = event["grant_type"] 

497 self.modify(self.CredentialType.ACCOUNT, account, account) 

498 

499 if id_token: 

500 idt = { 

501 "credential_type": self.CredentialType.ID_TOKEN, 

502 "secret": id_token, 

503 "home_account_id": home_account_id, 

504 "environment": environment, 

505 "realm": realm, 

506 "client_id": event.get("client_id"), 

507 # "authority": "it is optional", 

508 } 

509 self.modify(self.CredentialType.ID_TOKEN, idt, idt) 

510 

511 if refresh_token: 

512 rt = { 

513 "credential_type": self.CredentialType.REFRESH_TOKEN, 

514 "secret": refresh_token, 

515 "home_account_id": home_account_id, 

516 "environment": environment, 

517 "client_id": event.get("client_id"), 

518 "target": target, # Optional per schema though 

519 "last_modification_time": str(now), # Optional. Schema defines it as a string. 

520 } 

521 if "foci" in response: 

522 rt["family_id"] = response["foci"] 

523 self.modify(self.CredentialType.REFRESH_TOKEN, rt, rt) 

524 

525 app_metadata = { 

526 "client_id": event.get("client_id"), 

527 "environment": environment, 

528 } 

529 if "foci" in response: 

530 app_metadata["family_id"] = response.get("foci") 

531 self.modify(self.CredentialType.APP_METADATA, app_metadata, app_metadata) 

532 

533 def modify(self, credential_type, old_entry, new_key_value_pairs=None): 

534 # Modify the specified old_entry with new_key_value_pairs, 

535 # or remove the old_entry if the new_key_value_pairs is None. 

536 

537 # This helper exists to consolidate all token add/modify/remove behaviors, 

538 # so that the sub-classes will have only one method to work on, 

539 # instead of patching a pair of update_xx() and remove_xx() per type. 

540 # You can monkeypatch self.key_makers to support more types on-the-fly. 

541 key = self.key_makers[credential_type](**old_entry) 

542 with self._lock: 

543 if new_key_value_pairs: # Update with them 

544 entries = self._cache.setdefault(credential_type, {}) 

545 entries[key] = dict( 

546 old_entry, # Do not use entries[key] b/c it might not exist 

547 **new_key_value_pairs) 

548 else: # Remove old_entry 

549 self._cache.setdefault(credential_type, {}).pop(key, None) 

550 

551 def remove_rt(self, rt_item): 

552 assert rt_item.get("credential_type") == self.CredentialType.REFRESH_TOKEN 

553 return self.modify(self.CredentialType.REFRESH_TOKEN, rt_item) 

554 

555 def update_rt(self, rt_item, new_rt): 

556 assert rt_item.get("credential_type") == self.CredentialType.REFRESH_TOKEN 

557 return self.modify(self.CredentialType.REFRESH_TOKEN, rt_item, { 

558 "secret": new_rt, 

559 "last_modification_time": str(int(time.time())), # Optional. Schema defines it as a string. 

560 }) 

561 

562 def remove_at(self, at_item): 

563 assert at_item.get("credential_type") == self.CredentialType.ACCESS_TOKEN 

564 return self.modify(self.CredentialType.ACCESS_TOKEN, at_item) 

565 

566 def remove_idt(self, idt_item): 

567 assert idt_item.get("credential_type") == self.CredentialType.ID_TOKEN 

568 return self.modify(self.CredentialType.ID_TOKEN, idt_item) 

569 

570 def remove_account(self, account_item): 

571 assert "authority_type" in account_item 

572 return self.modify(self.CredentialType.ACCOUNT, account_item) 

573 

574 

575class SerializableTokenCache(TokenCache): 

576 """This serialization can be a starting point to implement your own persistence. 

577 

578 This class does NOT actually persist the cache on disk/db/etc.. 

579 Depending on your need, 

580 the following simple recipe for file-based, unencrypted persistence may be sufficient:: 

581 

582 import os, atexit, msal 

583 cache_filename = os.path.join( # Persist cache into this file 

584 os.getenv( 

585 # Automatically wipe out the cache from Linux when user's ssh session ends. 

586 # See also https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/690 

587 "XDG_RUNTIME_DIR", ""), 

588 "my_cache.bin") 

589 cache = msal.SerializableTokenCache() 

590 if os.path.exists(cache_filename): 

591 cache.deserialize(open(cache_filename, "r").read()) 

592 atexit.register(lambda: 

593 open(cache_filename, "w").write(cache.serialize()) 

594 # Hint: The following optional line persists only when state changed 

595 if cache.has_state_changed else None 

596 ) 

597 app = msal.ClientApplication(..., token_cache=cache) 

598 ... 

599 

600 Alternatively, you may use a more sophisticated cache persistence library, 

601 `MSAL Extensions <https://github.com/AzureAD/microsoft-authentication-extensions-for-python>`_, 

602 which provides token cache persistence with encryption, and more. 

603 

604 :var bool has_state_changed: 

605 Indicates whether the cache state in the memory has changed since last 

606 :func:`~serialize` or :func:`~deserialize` call. 

607 """ 

608 has_state_changed = False 

609 

610 def add(self, event, **kwargs): 

611 super(SerializableTokenCache, self).add(event, **kwargs) 

612 self.has_state_changed = True 

613 

614 def modify(self, credential_type, old_entry, new_key_value_pairs=None): 

615 super(SerializableTokenCache, self).modify( 

616 credential_type, old_entry, new_key_value_pairs) 

617 self.has_state_changed = True 

618 

619 def deserialize(self, state): 

620 # type: (Optional[str]) -> None 

621 """Deserialize the cache from a state previously obtained by serialize()""" 

622 with self._lock: 

623 self._cache = json.loads(state) if state else {} 

624 self.has_state_changed = False # reset 

625 

626 def serialize(self): 

627 # type: () -> str 

628 """Serialize the current cache state into a string.""" 

629 with self._lock: 

630 self.has_state_changed = False 

631 return json.dumps(self._cache, indent=4) 

632