AzureAD / microsoft-authentication-library-for-dotnet

Microsoft Authentication Library (MSAL) for .NET
https://aka.ms/msal-net
MIT License
1.36k stars 330 forks source link

[Feature Request] Allow updating the cached token before expiry #4808

Closed maskati closed 1 week ago

maskati commented 1 week ago

MSAL client type

Public, Confidential

Problem statement

MSAL does not currently seem to provide a mechanism to force the refresh of a cached access token before expiry. Such functionality would be useful in cases where the token is known to have changes, such as when group memberships are updated as a result of PIM for Groups.

Proposed solution

Change the implementation of WithForceRefresh(true) to also update the token cache. Updating the token cache would allow use of this function to refresh the currently cached token as used by other invocations utilizing the same cache (using the default WithForceRefresh(false)).

Alternatives

  1. Use WithForceRefresh(true) for all token acquisitions until cached token expiry.
  2. Clearing the cache and reauthenticating, which causes unnecessary effort considering that the refresh token was still valid, just unusable for cached token refresh.
rayluo commented 1 week ago

Change the implementation of WithForceRefresh(true) to also update the token cache

Does WithForceRefresh(true) not update the token cache? Any successful token acquisition should already update token cache. If not, that might be a bug.

That being said, forcing the calling app to use WithForceRefresh(true) is not a good dev experience, because calling app won't and shouldn't know when to force refresh. MSAL may revisit an AcquireToken(..., accessTokenToRenew=oldAccessToken) pattern.

bgavrilMS commented 1 week ago

WithForceRefresh(true) will result in MSAL ignoring any existing access token from the cache. Refresh Tokens are still used. New tokens from the STS will overwrite old tokens.

What flow are you testing with @maskati ? Public Clients using broker have spotty behavior for flag, but it should work on the latest versions of MSAL.NET

maskati commented 1 week ago

Now that I am testing it again it seems to be working as expected, and WithForceRefresh(true) is updating the cached token even while skipping the cache for lookup. Not sure under what circumstances I considered it not working when testing earlier.

A small note that it might be useful to update the documentation to indicate that force refresh does not skip the cache completely, and does in fact update the cache with the new token. I was performing my own tests because the behaviour was unclear based on the docs.