@@ -13,7 +13,7 @@ class AcquireTokenByManagedIdentitySupplier extends AuthenticationResultSupplier
1313
1414 private static final Logger LOG = LoggerFactory .getLogger (AcquireTokenByManagedIdentitySupplier .class );
1515
16- private static final int TWO_HOURS = 2 * 3600 ;
16+ private static final int TWO_HOURS = 2 * 3600 ;
1717
1818 private ManagedIdentityParameters managedIdentityParameters ;
1919
@@ -37,49 +37,66 @@ AuthenticationResult execute() throws Exception {
3737 clientApplication .serviceBundle ()
3838 );
3939
40- if (!managedIdentityParameters .forceRefresh ) {
41- LOG .debug ("ForceRefresh set to false. Attempting cache lookup" );
42-
43- try {
44- Set <String > scopes = new HashSet <>();
45- scopes .add (this .managedIdentityParameters .resource );
46- SilentParameters parameters = SilentParameters
47- .builder (scopes )
48- .tenant (managedIdentityParameters .tenant ())
49- .build ();
50-
51- RequestContext context = new RequestContext (
52- this .clientApplication ,
53- PublicApi .ACQUIRE_TOKEN_SILENTLY ,
54- parameters );
55-
56- SilentRequest silentRequest = new SilentRequest (
57- parameters ,
58- this .clientApplication ,
59- context ,
60- null );
61-
62- AcquireTokenSilentSupplier supplier = new AcquireTokenSilentSupplier (
63- this .clientApplication ,
64- silentRequest );
65-
66- return supplier .execute ();
67- } catch (MsalClientException ex ) {
68- if (ex .errorCode ().equals (AuthenticationErrorCode .CACHE_MISS )) {
69- LOG .debug (String .format ("Cache lookup failed: %s" , ex .getMessage ()));
70- return fetchNewAccessTokenAndSaveToCache (tokenRequestExecutor );
71- } else {
72- LOG .error (String .format ("Error occurred while cache lookup: %s" , ex .getMessage ()));
73- throw ex ;
74- }
75- }
40+ CacheRefreshReason cacheRefreshReason = CacheRefreshReason .NOT_APPLICABLE ;
41+
42+ if (managedIdentityParameters .forceRefresh ) {
43+ LOG .debug ("ForceRefresh set to true. Skipping cache lookup and attempting to acquire new token" );
44+ return fetchNewAccessTokenAndSaveToCache (tokenRequestExecutor , CacheRefreshReason .FORCE_REFRESH );
7645 }
7746
78- LOG .info ("Skipped looking for an Access Token in the cache because forceRefresh or Claims were set. " );
79- return fetchNewAccessTokenAndSaveToCache (tokenRequestExecutor );
47+
48+ LOG .debug ("ForceRefresh set to false. Attempting cache lookup" );
49+ try {
50+ Set <String > scopes = new HashSet <>();
51+ scopes .add (this .managedIdentityParameters .resource );
52+ SilentParameters parameters = SilentParameters
53+ .builder (scopes )
54+ .tenant (managedIdentityParameters .tenant ())
55+ .build ();
56+
57+ RequestContext context = new RequestContext (
58+ this .clientApplication ,
59+ PublicApi .ACQUIRE_TOKEN_SILENTLY ,
60+ parameters );
61+
62+ SilentRequest silentRequest = new SilentRequest (
63+ parameters ,
64+ this .clientApplication ,
65+ context ,
66+ null );
67+
68+ AcquireTokenSilentSupplier supplier = new AcquireTokenSilentSupplier (
69+ this .clientApplication ,
70+ silentRequest );
71+
72+ AuthenticationResult result = supplier .execute ();
73+ cacheRefreshReason = SilentRequestHelper .getCacheRefreshReasonIfApplicable (
74+ parameters ,
75+ result ,
76+ LOG );
77+
78+ // If the token does not need a refresh, return the cached token
79+ // Else refresh the token if it is either expired, proactively refreshable, or if the claims are passed.
80+ if (cacheRefreshReason == CacheRefreshReason .NOT_APPLICABLE ) {
81+ LOG .debug ("Returning token from cache" );
82+ result .metadata ().tokenSource (TokenSource .CACHE );
83+ return result ;
84+ } else {
85+ LOG .debug (String .format ("Refreshing access token. Cache refresh reason: %s" , cacheRefreshReason ));
86+ return fetchNewAccessTokenAndSaveToCache (tokenRequestExecutor , cacheRefreshReason );
87+ }
88+ } catch (MsalClientException ex ) {
89+ if (ex .errorCode ().equals (AuthenticationErrorCode .CACHE_MISS )) {
90+ LOG .debug (String .format ("Cache lookup failed: %s" , ex .getMessage ()));
91+ return fetchNewAccessTokenAndSaveToCache (tokenRequestExecutor , cacheRefreshReason );
92+ } else {
93+ LOG .error (String .format ("Error occurred while cache lookup: %s" , ex .getMessage ()));
94+ throw ex ;
95+ }
96+ }
8097 }
8198
82- private AuthenticationResult fetchNewAccessTokenAndSaveToCache (TokenRequestExecutor tokenRequestExecutor ) {
99+ private AuthenticationResult fetchNewAccessTokenAndSaveToCache (TokenRequestExecutor tokenRequestExecutor , CacheRefreshReason cacheRefreshReason ) throws Exception {
83100
84101 ManagedIdentityClient managedIdentityClient = new ManagedIdentityClient (msalRequest , tokenRequestExecutor .getServiceBundle ());
85102
@@ -91,13 +108,17 @@ private AuthenticationResult fetchNewAccessTokenAndSaveToCache(TokenRequestExecu
91108
92109 AuthenticationResult authenticationResult = createFromManagedIdentityResponse (managedIdentityResponse );
93110 clientApplication .tokenCache .saveTokens (tokenRequestExecutor , authenticationResult , clientApplication .authenticationAuthority .host );
94- return authenticationResult ;
111+ AuthenticationResult result = authenticationResult ;
112+ result .metadata ().tokenSource (TokenSource .IDENTITY_PROVIDER );
113+ result .metadata ().cacheRefreshReason (cacheRefreshReason );
114+ return result ;
95115 }
96116
97117 private AuthenticationResult createFromManagedIdentityResponse (ManagedIdentityResponse managedIdentityResponse ) {
98118 long expiresOn = Long .parseLong (managedIdentityResponse .expiresOn );
99119 long refreshOn = calculateRefreshOn (expiresOn );
100120 AuthenticationResultMetadata metadata = AuthenticationResultMetadata .builder ()
121+ .tokenSource (TokenSource .IDENTITY_PROVIDER )
101122 .refreshOn (refreshOn )
102123 .build ();
103124
@@ -111,7 +132,7 @@ private AuthenticationResult createFromManagedIdentityResponse(ManagedIdentityRe
111132 .build ();
112133 }
113134
114- private long calculateRefreshOn (long expiresOn ){
135+ private long calculateRefreshOn (long expiresOn ) {
115136 long timestampSeconds = System .currentTimeMillis () / 1000 ;
116137 long expiresIn = expiresOn - timestampSeconds ;
117138
0 commit comments