My WebAPI application gets a token from a service on start-up. This token is then to be used in a shared HTTP Client to prevent port exhaustion.
When this token is about to expire, I want to get a new one and save it in my service for re-use.
In my implementation, a token is retrieved - however it has the same expiry as the original token:
// Retrieve the token and assign to AuthenticationResult
private async Task GetAPIToken()
{
AuthenticationContext authContext = new AuthenticationContext(Authority);
var clientCredential = new ClientCredential(clientId, clientSecret);
// Same token after multiple calls
AuthenticationResult = await authContext.AcquireTokenAsync(resourceId, clientCredential).ConfigureAwait(false);
}
How can I save the latest authentication token?
Task.Run(async () => await GetAPIToken()).Wait();
instead ofGetAPIToken().Wait();
? – SeptupletAuthenticationResult
property, and not happening something else like the retrieved value being already expired upon arrival? – Septuplet.wait()
alone would run synchronously. Yep I'm sure the latest token which is retrieved is correct.. the static token's expiration is the same as when it's first retrieved, even though a new request has come in and renewed it – TamikatamikoAuthenticationResult
property. The only worrisome point is that theAuthenticationResult
is not always accessed while holding thelock
, so it's not accessed with volatile semantics. But I doubt that converting it to avolatile
field (private static volatile AuthenticationResult AuthenticationResult;
) will fix the issue. Honestly there are lots of things that I don't like in your code, but nevertheless it should work as expected. – SeptupletAsyncExpiringLazy<T>
type found in this package. – SeptupletAuthenticationResult
eventually update? Or are you saying it never updates? How do you know it doesn't? Have you traced your calls toGetAPIToken
? And...
isn't valid code - can you show the rest of the method please? – BobettebobinaGetAPIToken
made me realise the AuthContext was holding onto the token. I'll update with an answer – Tamikatamiko