Skip to content

Commit 3d2db10

Browse files
authored
Merge pull request #328 from microsoft/users/tracyboehrer/non-jwt-token-fix
Handling non-JWT token during OAuth by not caching
2 parents 01aa415 + 6159928 commit 3d2db10

File tree

1 file changed

+29
-14
lines changed

1 file changed

+29
-14
lines changed

src/libraries/Client/Microsoft.Agents.Connector/RestClients/UserTokenRestClient.cs

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -406,8 +406,11 @@ private static TokenResponse GetTokenResponseFromCache(string cacheKey)
406406
var value = _cache.Get(cacheKey);
407407
if (value != null)
408408
{
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.
409412
var toExpiration = ((TokenResponse)value).Expiration - DateTimeOffset.UtcNow;
410-
if (toExpiration?.TotalMinutes >= 5) // Align with sliding expiration
413+
if (toExpiration?.TotalMinutes >= 5)
411414
{
412415
return (TokenResponse)value;
413416
}
@@ -422,22 +425,34 @@ private static void AddTokenResponseToCache(string cacheKey, TokenResponse token
422425
{
423426
if (tokenResponse != null && tokenResponse.Token != null)
424427
{
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)
430440
{
431-
// Token Service isn't returning Expiration in TokenResponse
432-
tokenResponse.Expiration = jwtToken.ValidTo;
441+
tokenResponse.IsExchangeable = false;
433442
}
434443

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+
}
441456
}
442457
}
443458

0 commit comments

Comments
 (0)