-
Notifications
You must be signed in to change notification settings - Fork 19
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
Eliminate token cache timeout setting in most cases #126
Open
vvdb-architecture
wants to merge
3
commits into
GFlisch:master
Choose a base branch
from
vvdb-architecture:feature/EliminateTokenCacheTimeout
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,18 @@ | ||
using System.Collections.Generic; | ||
using System; | ||
using System.Diagnostics; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Globalization; | ||
using System.Linq; | ||
using System.Security.Claims; | ||
using System.Threading.Tasks; | ||
using Arc4u.Configuration; | ||
using Arc4u.Dependency.Attribute; | ||
using Arc4u.Diagnostics; | ||
using Arc4u.IdentityModel.Claims; | ||
using Arc4u.OAuth2.Options; | ||
using Arc4u.OAuth2.Token; | ||
using Arc4u.Security.Principal; | ||
using Arc4u.Standard.OAuth2.Security; | ||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Arc4u.OAuth2; | ||
|
||
|
@@ -102,8 +98,6 @@ public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) | |
} | ||
|
||
#region Handling extra claims | ||
private const string tokenExpirationClaimType = "exp"; | ||
private static readonly string[] ClaimsToExclude = { "aud", "iss", "iat", "nbf", "acr", "aio", "appidacr", "ipaddr", "scp", "sub", "tid", "uti", "unique_name", "apptype", "appid", "ver", "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant", "http://schemas.microsoft.com/identity/claims/scope" }; | ||
|
||
/// <summary> | ||
/// This code is similar to the code in AppPrincipalFactory where the claims are stored in a secureCache. | ||
|
@@ -128,21 +122,12 @@ private async Task LoadExtraClaimsAsync(ClaimsIdentity? identity) | |
// Something already in the cache? Avoid a expensive backend call. | ||
var cachedClaims = GetClaimsFromCache(cacheKey); | ||
|
||
// check expirity. | ||
var cachedExpiredClaim = cachedClaims.FirstOrDefault(c => c.ClaimType.Equals(tokenExpirationClaimType, StringComparison.OrdinalIgnoreCase)); | ||
|
||
if (cachedExpiredClaim is not null && long.TryParse(cachedExpiredClaim.Value, out var cachedExpiredTicks)) | ||
// if cachedClaims is not null, it means that the information was in the cache and didn't expire yet. | ||
if (cachedClaims is not null) | ||
{ | ||
var expDate = DateTimeOffset.FromUnixTimeSeconds(cachedExpiredTicks).UtcDateTime; | ||
if (expDate > DateTime.UtcNow) | ||
{ | ||
identity.AddClaims(cachedClaims.Where(c => c.ClaimType != tokenExpirationClaimType) | ||
.Where(c => !ClaimsToExclude.Any(arg => arg.Equals(c.ClaimType))) | ||
.Where(c => !identity.Claims.Any(c1 => c1.Type == c.ClaimType)) | ||
.Select(c => new Claim(c.ClaimType, c.Value))); | ||
|
||
return; | ||
} | ||
// Add the new claims to the identity. Note that we need to merge the same way as in the case they are retrieved (see below) | ||
identity.MergeClaims(cachedClaims); | ||
return; | ||
} | ||
|
||
// Add Telemetry. | ||
|
@@ -154,65 +139,70 @@ private async Task LoadExtraClaimsAsync(ClaimsIdentity? identity) | |
// Should receive specific extra claims. This is the responsibility of the caller to provide the right claims. | ||
// We expect the exp claim to be present. | ||
// if not the persistence time will be the default one. | ||
var claims = (await _claimsFiller.GetAsync(identity, settings, null).ConfigureAwait(false)).Where(c => !ClaimsToExclude.Any(arg => arg.Equals(c.ClaimType))).ToList(); | ||
var claims = (await _claimsFiller.GetAsync(identity, settings, null).ConfigureAwait(false)).Sanitize().ToList(); | ||
|
||
// Load the claims into the identity but exclude the exp claim and the one already present. | ||
identity.AddClaims(claims.Where(c => c.ClaimType != tokenExpirationClaimType) | ||
.Where(c => !ClaimsToExclude.Any(arg => arg.Equals(c.ClaimType))) | ||
.Where(c => !identity.Claims.Any(c1 => c1.Type == c.ClaimType)) | ||
.Select(c => new Claim(c.ClaimType, c.Value))); | ||
identity.MergeClaims(claims); | ||
|
||
SaveClaimsToCache(claims, cacheKey); | ||
} | ||
TimeSpan timeout; | ||
|
||
} | ||
|
||
private List<ClaimDto> GetClaimsFromCache(string? cacheKey) | ||
{ | ||
var claims = new List<ClaimDto>(); | ||
// Check expiry claim explicitly returned in the call to _claimsFiller.GetAsync | ||
// If no expiry claim found in the call to _claimsFiller.GetAsync, try to locate one in the existing identity claims (which are normally obtained from the bearer token) | ||
if (claims.TryGetExpiration(out var ticks) || identity.Claims.TryGetExpiration(out ticks)) | ||
{ | ||
// there's an expiration claim in the claims returned by the claims filler or in the existing identity claims, so we can compute an expiration date | ||
timeout = DateTimeOffset.FromUnixTimeSeconds(ticks) - DateTimeOffset.UtcNow; | ||
} | ||
else | ||
{ | ||
// fall back to the configured max time. | ||
timeout = _options.MaxTime; | ||
} | ||
|
||
if (string.IsNullOrWhiteSpace(cacheKey)) | ||
{ | ||
return claims; | ||
SaveClaimsToCache(claims, cacheKey, timeout); | ||
} | ||
} | ||
|
||
try | ||
{ | ||
claims = _cacheHelper.GetCache().Get<List<ClaimDto>>(cacheKey) ?? new List<ClaimDto>(); | ||
} | ||
catch (Exception ex) | ||
private List<ClaimDto>? GetClaimsFromCache(string? cacheKey) | ||
{ | ||
if (!string.IsNullOrWhiteSpace(cacheKey)) | ||
{ | ||
_logger.Technical().Exception(ex).Log(); | ||
try | ||
{ | ||
return _cacheHelper.GetCache().Get<List<ClaimDto>>(cacheKey); | ||
} | ||
catch (Exception ex) | ||
{ | ||
_logger.Technical().Exception(ex).Log(); | ||
} | ||
} | ||
|
||
return claims; | ||
return null; | ||
} | ||
|
||
private void SaveClaimsToCache([DisallowNull] IEnumerable<ClaimDto> claims, string? cacheKey) | ||
private void SaveClaimsToCache([DisallowNull] IEnumerable<ClaimDto> claims, string? cacheKey, TimeSpan timeout) | ||
{ | ||
if (string.IsNullOrWhiteSpace(cacheKey)) | ||
{ | ||
return; | ||
} | ||
|
||
// Only if the cache key is valid does it make sense to test the claims validity | ||
ArgumentNullException.ThrowIfNull(claims); | ||
|
||
try | ||
if (timeout > TimeSpan.Zero) | ||
{ | ||
var cachedExpiredClaim = claims.FirstOrDefault(c => c.ClaimType.Equals(tokenExpirationClaimType, StringComparison.OrdinalIgnoreCase)); | ||
|
||
// if no expiration claim exist we assume the lifetime of the extra claims is defined by the cache context for the principal. | ||
if (cachedExpiredClaim is null) | ||
try | ||
{ | ||
cachedExpiredClaim = new ClaimDto(tokenExpirationClaimType, DateTimeOffset.UtcNow.Add(_cacheOptions.MaxTime).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); | ||
claims = new List<ClaimDto>(claims) { cachedExpiredClaim }; | ||
_cacheHelper.GetCache().Put(cacheKey, timeout, claims); | ||
} | ||
catch (Exception ex) | ||
{ | ||
_logger.Technical().Exception(ex).Log(); | ||
Comment on lines
+196
to
+200
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Avoid catching general exceptions In the cache save operation, catching the general |
||
} | ||
|
||
_cacheHelper.GetCache().Put(cacheKey, _cacheOptions.MaxTime, claims); | ||
} | ||
catch (Exception ex) | ||
else | ||
{ | ||
_logger.Technical().Exception(ex).Log(); | ||
_logger.Technical().LogWarning("The timeout is not valid to save the claims in the cache."); | ||
} | ||
} | ||
#endregion | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Avoid catching general exceptions
Catching the general
Exception
type may mask specific issues and make debugging more difficult. Consider catching more specific exceptions that are expected from the cache retrieval operation.