Skip to content

Commit

Permalink
Remove request path from caching of jwt token
Browse files Browse the repository at this point in the history
  • Loading branch information
majco333 committed Sep 27, 2022
1 parent 3ec7f08 commit 57519bc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,14 @@ private async Task<string> GetUserAuthorizationJwtAsync(
IMemoryCache memoryCache,
IServiceDiscoveryProvider serviceDiscoveryProvider)
{
if (JwtAuthorizationHelper.TryGetTokenValue(httpContext.Request.Headers, out string value))
if (JwtAuthorizationHelper.TryGetTokenValue(httpContext.Request.Headers, out string token))
{
int key = CacheHttpHeadersHelper.TryGetValue(
httpContext.Request.Headers,
_jwtAuthorizationOptions.CacheKeyHttpHeaders,
out string cacheKeyPart)
? GetKey(httpContext, value, cacheKeyPart)
: GetKey(httpContext, value);
? GetKey(token, cacheKeyPart)
: GetKey(token);

if (!memoryCache.TryGetValue(key, out string jwtToken))
{
Expand All @@ -89,7 +89,7 @@ private async Task<string> GetUserAuthorizationJwtAsync(
httpContext,
httpClientFactory,
memoryCache,
value,
token,
key,
authUrl);
}
Expand All @@ -99,7 +99,7 @@ private async Task<string> GetUserAuthorizationJwtAsync(
else if (!string.IsNullOrEmpty(_jwtAuthorizationOptions.HashParameterName)
&& httpContext.Request.Query.TryGetValue(_jwtAuthorizationOptions.HashParameterName, out StringValues hashValue))
{
int key = GetKey(httpContext, hashValue.ToString());
int key = GetKey(hashValue.ToString());
if (!memoryCache.TryGetValue(key, out string jwtToken))
{
var uriBuilder = new UriBuilder(_jwtAuthorizationOptions.GetHashAuthorization(serviceDiscoveryProvider));
Expand Down Expand Up @@ -186,11 +186,8 @@ private bool IsCacheAllowed()
=> _jwtAuthorizationOptions.CacheSlidingExpirationOffset != TimeSpan.Zero
|| _jwtAuthorizationOptions.CacheAbsoluteExpiration != TimeSpan.Zero;

internal static int GetKey(HttpContext httpContext, StringValues value)
=> HashCode.Combine(value, httpContext.Request.Path);

internal static int GetKey(HttpContext httpContext, StringValues value, string additionalKeyPart)
=> HashCode.Combine(value, httpContext.Request.Path, additionalKeyPart);
internal static int GetKey(StringValues value, string additionalKeyPart = null)
=> (additionalKeyPart is null) ? HashCode.Combine(value) : HashCode.Combine(value, additionalKeyPart);

private void AddUserProfileClaimsToIdentityAndHttpHeaders(HttpContext httpContext, string userJwtToken)
=> httpContext.Request.Headers[HeaderNames.Authorization] = $"{JwtAuthorizationHelper.AuthTokenPrefix} {userJwtToken}";
Expand Down
2 changes: 1 addition & 1 deletion src/Kros.AspNetCore/Kros.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFrameworks>net6.0;netcoreapp3.1</TargetFrameworks>
<Version>3.2.1</Version>
<Version>3.3.0</Version>
<Description>General utilities and helpers for building ASP.NET Core WEB API</Description>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public async void UseCachedJwtToken()

var context = new DefaultHttpContext();
var cache = new MemoryCache(new MemoryCacheOptions());
cache.Set(HashCode.Combine(accessToken, context.Request.Path), "AAAAAA");
cache.Set(HashCode.Combine(accessToken), "AAAAAA");

context.Request.Headers.Add(HeaderNames.Authorization, "access_token");
await middleware.Invoke(context, httpClientFactoryMock, cache, CreateProvider());
Expand All @@ -191,7 +191,7 @@ public async void UseCachedJwtTokenForHash()
context.Request.Query = new QueryCollection(QueryHelpers.ParseQuery("?hash=asdf"));

var cache = new MemoryCache(new MemoryCacheOptions());
cache.Set(HashCode.Combine(context.Request.Query["hash"].ToString(), context.Request.Path), "BBQ");
cache.Set(HashCode.Combine(context.Request.Query["hash"].ToString()), "BBQ");

await middleware.Invoke(context, httpClientFactoryMock, cache, CreateProvider());

Expand All @@ -214,7 +214,7 @@ public async void CachesJwtToken()
context.Request.Headers.Add(HeaderNames.Authorization, "access_token");
await middleware.Invoke(context, httpClientFactoryMock, cache, CreateProvider());

cache.Get(HashCode.Combine(accessToken, context.Request.Path))
cache.Get(HashCode.Combine(accessToken))
.Should()
.Be(JwtToken);
}
Expand All @@ -230,7 +230,7 @@ public async void CachesJwtTokenForHash()

await middleware.Invoke(context, httpClientFactoryMock, cache, CreateProvider());

cache.Get(HashCode.Combine(context.Request.Query["hash"].ToString(), context.Request.Path))
cache.Get(HashCode.Combine(context.Request.Query["hash"].ToString()))
.Should()
.Be(HashJwtToken);
}
Expand All @@ -251,8 +251,7 @@ public async void JwtTokenWithoutCaching()
context.Request.Method = HttpMethod.Get.ToString();
await middleware.Invoke(context, httpClientFactoryMock, cache, CreateProvider());

var aaa = cache.Get(HashCode.Combine(accessToken, context.Request.Path));
cache.Get(HashCode.Combine(accessToken, context.Request.Path))
cache.Get(HashCode.Combine(accessToken))
.Should()
.BeNull();
}
Expand Down Expand Up @@ -387,7 +386,7 @@ public async void JwtTokenDoesNotContainConnectionId(string connectionId)
[InlineData(null)]
[InlineData("")]
[InlineData("connection_id")]
public async void CacheJwtTokenWithConnectionId(string connectionId)
public async void CacheJwtToken(string connectionId)
{
(var httpClientFactoryMock, var middleware) = CreateMiddleware(
HttpStatusCode.OK,
Expand All @@ -406,8 +405,8 @@ public async void CacheJwtTokenWithConnectionId(string connectionId)
context.Request.Headers.Add("any-header", connectionId);

int key = connectionId == null
? GatewayAuthorizationMiddleware.GetKey(context, accessToken)
: GatewayAuthorizationMiddleware.GetKey(context, accessToken, connectionId);
? GatewayAuthorizationMiddleware.GetKey(accessToken)
: GatewayAuthorizationMiddleware.GetKey(accessToken, connectionId);

var memoryCache = new MemoryCache(new MemoryCacheOptions());
memoryCache.Set(key, $"{JwtToken}");
Expand Down

0 comments on commit 57519bc

Please sign in to comment.