Skip to content

Commit e4b41f1

Browse files
Add disable access token cache config
Added support for disabling access token cache configuration.
1 parent 1ecba3b commit e4b41f1

File tree

4 files changed

+58
-2
lines changed

4 files changed

+58
-2
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,14 @@ Authentication using OAuth2.
7575

7676
##### Client credentials
7777

78-
Using OAuth2 client credentials, all settings except `Scope` is required.
78+
Using OAuth2 client credentials, all settings except `DisableTokenCache` and `Scope` is required.
7979

8080
```
8181
"<section name>": {
8282
"AuthenticationProvider": "OAuth2",
8383
"OAuth2": {
8484
"AuthorizationEndpoint": "<OAuth2 token endpoint>",
85+
"DisableTokenCache": false,
8586
"GrantType": "ClientCredentials",
8687
"Scope": "<Optional scopes separated by space>",
8788
"ClientCredentials": {

src/HttpClientAuthentication/Configuration/OAuth2Configuration.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ public sealed class OAuth2Configuration
2424
/// </summary>
2525
public string? AuthorizationScheme { get; set; }
2626

27+
/// <summary>
28+
/// Gets or sets if the access token should be cached or not.
29+
/// </summary>
30+
public bool DisableTokenCache { get; set; }
31+
2732
/// <summary>
2833
/// Gets or sets the type of grant flow to be used.
2934
/// </summary>

src/HttpClientAuthentication/Helpers/OAuth2Provider.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,12 @@ public OAuth2Provider(IHttpClientFactory clientFactory, ILogger<OAuth2Provider>
7979
return null;
8080
}
8181

82-
if (token.ExpiresIn > 0)
82+
if (configuration.DisableTokenCache)
83+
{
84+
_logger.LogInformation("Token retrieved from {AuthorizationEndpoint} with client id {ClientId}, but the token cache is disabled.",
85+
configuration.AuthorizationEndpoint, configuration.ClientCredentials!.ClientId);
86+
}
87+
else if (token.ExpiresIn > 0)
8388
{
8489
double cacheExpiresIn = (int)token.ExpiresIn * 0.95;
8590
_memoryCache.Set(cacheKey, token, TimeSpan.FromSeconds(cacheExpiresIn));

test/HttpClientAuthentication.Test/Helpers/OAuth2ProviderTests/GetClientCredentialsAccessTokenAsyncTests.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,51 @@ public async Task TestNoCachingOfAccessTokenResponseWithMissingExpiresIn()
246246
"https://somehost/", "client_id"), Times.Once);
247247
}
248248

249+
[Fact]
250+
public async Task TestNoCachingOfAccessTokenResponseWhenCacheIsDiabled()
251+
{
252+
IServiceProvider services = BuildServices();
253+
254+
AccessTokenResponse expected = new()
255+
{
256+
AccessToken = "ACCESS_TOKEN",
257+
TokenType = "TOKEN_TYPE",
258+
ExpiresIn = null
259+
};
260+
261+
Mock<HttpClient> httpClientMock = services.GetRequiredService<Mock<HttpClient>>();
262+
263+
httpClientMock.Setup(httpClient => httpClient.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>()))
264+
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
265+
{
266+
Content = JsonContent.Create(expected)
267+
});
268+
269+
OAuth2Configuration configuration = new()
270+
{
271+
GrantType = OAuth2GrantType.ClientCredentials,
272+
AuthorizationEndpoint = new("https://somehost/"),
273+
ClientCredentials = new()
274+
{
275+
ClientId = "client_id",
276+
ClientSecret = "client_secret"
277+
},
278+
DisableTokenCache = true
279+
};
280+
281+
OAuth2Provider provider = services.GetRequiredService<OAuth2Provider>();
282+
283+
await provider.GetClientCredentialsAccessTokenAsync(configuration, default).ConfigureAwait(false);
284+
285+
Mock<IMemoryCache> memoryCacheMock = services.GetRequiredService<Mock<IMemoryCache>>();
286+
memoryCacheMock.Verify(memoryCache => memoryCache.CreateEntry("ClientCredentials#https://somehost/#client_id"), Times.Never);
287+
288+
Mock<ILogger<OAuth2Provider>> loggerMock = services.GetRequiredService<Mock<ILogger<OAuth2Provider>>>();
289+
290+
loggerMock.VerifyExt(l => l.LogInformation("Token retrieved from {AuthorizationEndpoint} with client id {ClientId}, but the token cache is disabled.",
291+
"https://somehost/", "client_id"), Times.Once);
292+
}
293+
249294
[Fact]
250295
public async Task TestUseFormBasedAuthentication()
251296
{

0 commit comments

Comments
 (0)