Skip to content

Handling non-JWT token during OAuth by not caching #328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 13, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,11 @@ private static TokenResponse GetTokenResponseFromCache(string cacheKey)
var value = _cache.Get(cacheKey);
if (value != null)
{
// Token Service will renew within 5 minutes of expiration. Return the cached token
// if there is more than that. Otherwise, remove it from the cache and return null. This
// will result in a call to the Token Service to get a new token.
var toExpiration = ((TokenResponse)value).Expiration - DateTimeOffset.UtcNow;
if (toExpiration?.TotalMinutes >= 5) // Align with sliding expiration
if (toExpiration?.TotalMinutes >= 5)
{
return (TokenResponse)value;
}
Expand All @@ -422,22 +425,34 @@ private static void AddTokenResponseToCache(string cacheKey, TokenResponse token
{
if (tokenResponse != null && tokenResponse.Token != null)
{
var jwtToken = new JwtSecurityToken(tokenResponse.Token);

tokenResponse.IsExchangeable = IsExchangeableToken(jwtToken);

if (tokenResponse.Expiration == null)
try
{
var jwtToken = new JwtSecurityToken(tokenResponse.Token);
if (tokenResponse.Expiration == null)
{
// It's usually the case that the TokenResponse will NOT include an expiration value,
// in which case we will use the JWT token expiration value.
tokenResponse.Expiration = jwtToken.ValidTo;
}
tokenResponse.IsExchangeable = IsExchangeableToken(jwtToken);
}
catch (Exception)
{
// Token Service isn't returning Expiration in TokenResponse
tokenResponse.Expiration = jwtToken.ValidTo;
tokenResponse.IsExchangeable = false;
}

_cache.Add(
new CacheItem(cacheKey) { Value = tokenResponse },
new CacheItemPolicy()
{
SlidingExpiration = TimeSpan.FromMinutes(5)
});
// If the TokenResponse doesn't contain an expiration value then expiration calcs
// won't be available to callers. But the token can otherwise be used. However,
// we'll skip caching for now.
if (tokenResponse.Expiration != null)
{
_cache.Add(
new CacheItem(cacheKey) { Value = tokenResponse },
new CacheItemPolicy()
{
SlidingExpiration = TimeSpan.FromMinutes(5)
});
}
}
}

Expand Down
Loading