@@ -406,8 +406,11 @@ private static TokenResponse GetTokenResponseFromCache(string cacheKey)
406
406
var value = _cache . Get ( cacheKey ) ;
407
407
if ( value != null )
408
408
{
409
+ // Token Service will renew within 5 minutes of expiration. Return the cached token
410
+ // if there is more than that. Otherwise, remove it from the cache and return null. This
411
+ // will result in a call to the Token Service to get a new token.
409
412
var toExpiration = ( ( TokenResponse ) value ) . Expiration - DateTimeOffset . UtcNow ;
410
- if ( toExpiration ? . TotalMinutes >= 5 ) // Align with sliding expiration
413
+ if ( toExpiration ? . TotalMinutes >= 5 )
411
414
{
412
415
return ( TokenResponse ) value ;
413
416
}
@@ -422,22 +425,34 @@ private static void AddTokenResponseToCache(string cacheKey, TokenResponse token
422
425
{
423
426
if ( tokenResponse != null && tokenResponse . Token != null )
424
427
{
425
- var jwtToken = new JwtSecurityToken ( tokenResponse . Token ) ;
426
-
427
- tokenResponse . IsExchangeable = IsExchangeableToken ( jwtToken ) ;
428
-
429
- if ( tokenResponse . Expiration == null )
428
+ try
429
+ {
430
+ var jwtToken = new JwtSecurityToken ( tokenResponse . Token ) ;
431
+ if ( tokenResponse . Expiration == null )
432
+ {
433
+ // It's usually the case that the TokenResponse will NOT include an expiration value,
434
+ // in which case we will use the JWT token expiration value.
435
+ tokenResponse . Expiration = jwtToken . ValidTo ;
436
+ }
437
+ tokenResponse . IsExchangeable = IsExchangeableToken ( jwtToken ) ;
438
+ }
439
+ catch ( Exception )
430
440
{
431
- // Token Service isn't returning Expiration in TokenResponse
432
- tokenResponse . Expiration = jwtToken . ValidTo ;
441
+ tokenResponse . IsExchangeable = false ;
433
442
}
434
443
435
- _cache . Add (
436
- new CacheItem ( cacheKey ) { Value = tokenResponse } ,
437
- new CacheItemPolicy ( )
438
- {
439
- SlidingExpiration = TimeSpan . FromMinutes ( 5 )
440
- } ) ;
444
+ // If the TokenResponse doesn't contain an expiration value then expiration calcs
445
+ // won't be available to callers. But the token can otherwise be used. However,
446
+ // we'll skip caching for now.
447
+ if ( tokenResponse . Expiration != null )
448
+ {
449
+ _cache . Add (
450
+ new CacheItem ( cacheKey ) { Value = tokenResponse } ,
451
+ new CacheItemPolicy ( )
452
+ {
453
+ SlidingExpiration = TimeSpan . FromMinutes ( 5 )
454
+ } ) ;
455
+ }
441
456
}
442
457
}
443
458
0 commit comments