-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathAcquireTokenSilentlyTest.java
More file actions
290 lines (209 loc) · 14 KB
/
AcquireTokenSilentlyTest.java
File metadata and controls
290 lines (209 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.aad.msal4j;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
class AcquireTokenSilentlyTest {
Account basicAccount = new Account("home_account_id", "login.windows.net", "username", null);
String cache = TestHelper.readResource(this.getClass(), "/AAD_cache_data/full_cache.json");
@Test
void publicAppAcquireTokenSilently_emptyCache_MsalClientException() throws Throwable {
PublicClientApplication application = PublicClientApplication
.builder(TestConfiguration.AAD_CLIENT_ID)
.b2cAuthority(TestConfiguration.B2C_AUTHORITY).build();
SilentParameters parameters = SilentParameters.builder(Collections.singleton("scope")).build();
CompletableFuture<IAuthenticationResult> future = application.acquireTokenSilently(parameters);
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalClientException.class, ex.getCause());
assertTrue(ex.getMessage().contains(AuthenticationErrorMessage.NO_TOKEN_IN_CACHE));
}
@Test
void confidentialAppAcquireTokenSilently_emptyCache_MsalClientException() throws Throwable {
ConfidentialClientApplication application = ConfidentialClientApplication
.builder(TestConfiguration.AAD_CLIENT_ID, ClientCredentialFactory.createFromSecret(TestConfiguration.AAD_CLIENT_DUMMYSECRET))
.b2cAuthority(TestConfiguration.B2C_AUTHORITY).build();
SilentParameters parameters = SilentParameters.builder(Collections.singleton("scope")).build();
CompletableFuture<IAuthenticationResult> future = application.acquireTokenSilently(parameters);
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalClientException.class, ex.getCause());
assertTrue(ex.getMessage().contains(AuthenticationErrorMessage.NO_TOKEN_IN_CACHE));
}
@Test
void publicAppAcquireTokenSilently_claimsSkipCache() throws Throwable {
PublicClientApplication application = PublicClientApplication.builder("client_id")
.instanceDiscovery(false)
.authority("https://some.authority.com/realm")
.build();
application.tokenCache.deserialize(cache);
SilentParameters parameters = SilentParameters.builder(Collections.singleton("scopes"), basicAccount).build();
IAuthenticationResult result = application.acquireTokenSilently(parameters).get();
//Confirm cached dummy token returned from silent request
assertNotNull(result);
assertEquals("token", result.accessToken());
ClaimsRequest cr = new ClaimsRequest();
cr.requestClaimInAccessToken("something", null);
parameters = SilentParameters.builder(Collections.singleton("scopes"), basicAccount).claims(cr).build();
CompletableFuture<IAuthenticationResult> future = application.acquireTokenSilently(parameters);
//Confirm cached dummy token ignored when claims are part of request
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalInteractionRequiredException.class, ex.getCause());
}
@Test
void confidentialAppAcquireTokenSilently_claimsSkipCache() throws Throwable {
ConfidentialClientApplication application = ConfidentialClientApplication
.builder("client_id", ClientCredentialFactory.createFromSecret(TestConfiguration.AAD_CLIENT_DUMMYSECRET))
.instanceDiscovery(false)
.authority("https://some.authority.com/realm").build();
application.tokenCache.deserialize(cache);
SilentParameters parameters = SilentParameters.builder(Collections.singleton("scopes"), basicAccount).build();
IAuthenticationResult result = application.acquireTokenSilently(parameters).get();
assertNotNull(result);
assertEquals("token", result.accessToken());
ClaimsRequest cr = new ClaimsRequest();
cr.requestClaimInAccessToken("something", null);
parameters = SilentParameters.builder(Collections.singleton("scopes"), basicAccount).claims(cr).build();
CompletableFuture<IAuthenticationResult> future = application.acquireTokenSilently(parameters);
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalInteractionRequiredException.class, ex.getCause());
}
@Test
void testTokenRefreshReasons() throws Exception {
DefaultHttpClient httpClientMock = mock(DefaultHttpClient.class);
ConfidentialClientApplication cca = TestHelper.buildCca(httpClientMock);
HashMap<String, String> responseParameters = new HashMap<>();
//Acquire a token that expires at the same time it is acquired, so it will expire before the next acquire token call
responseParameters.put("access_token", "expiredToken");
responseParameters.put("id_token", TestHelper.createIdToken(new HashMap<>()));
responseParameters.put("expires_in", "0");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
OnBehalfOfParameters parameters = OnBehalfOfParameters.builder(Collections.singleton("someScopes"), new UserAssertion(TestHelper.signedAssertion)).build();
IAuthenticationResult result = cca.acquireToken(parameters).get();
//There should be one token in the cache, and no refresh behavior should have happened yet
assertRefreshedToken(result, "expiredToken", CacheRefreshReason.NOT_APPLICABLE, cca.tokenCache.accessTokens.size());
//Attempt to retrieve the cached token, however it is expired and should be refreshed.
// In this test, it will be replaced with a token that expires in 1 minute
responseParameters.put("access_token", "nearlyExpiredToken");
responseParameters.put("expires_in", "60");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
SilentParameters silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).build();
result = cca.acquireTokenSilently(silentParameters).get();
//Ensure there is still one token in the cache, however it is the new refreshed token rather than the token from the first mocked call
assertRefreshedToken(result, "nearlyExpiredToken", CacheRefreshReason.EXPIRED, cca.tokenCache.accessTokens.size());
//Attempt to retrieve the cached token, however it is within the 5-minute buffer and should be refreshed.
// In this test, it will be replaced with a token that expires in 1 hour but has a refresh_in time of 1 second
responseParameters.put("access_token", "refreshInToken");
responseParameters.put("expires_in", "3600");
responseParameters.put("refresh_in", "1");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).build();
result = cca.acquireTokenSilently(silentParameters).get();
assertRefreshedToken(result, "refreshInToken", CacheRefreshReason.EXPIRED, cca.tokenCache.accessTokens.size());
//Attempt to retrieve the cached token, however it is within the 5-minute buffer and should be refreshed.
// In this test, it will be replaced with a token that expires in 1 hour (and does not have a valid refresh_in time)
responseParameters.put("access_token", "normalToken");
responseParameters.put("expires_in", "3600");
responseParameters.put("refresh_in", "0");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
//refresh_in values are in seconds, so we must wait to guarantee it is past the proactive refresh time
TimeUnit.SECONDS.sleep(2);
silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).build();
result = cca.acquireTokenSilently(silentParameters).get();
assertRefreshedToken(result, "normalToken", CacheRefreshReason.PROACTIVE_REFRESH, cca.tokenCache.accessTokens.size());
//Force the token to be refreshed
responseParameters.put("access_token", "forcedRefreshToken");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).forceRefresh(true).build();
result = cca.acquireTokenSilently(silentParameters).get();
assertRefreshedToken(result, "forcedRefreshToken", CacheRefreshReason.FORCE_REFRESH, cca.tokenCache.accessTokens.size());
//Finally, force a refresh by setting claims
responseParameters.put("access_token", "claimsToken");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);
silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).claims(new ClaimsRequest()).build();
result = cca.acquireTokenSilently(silentParameters).get();
assertRefreshedToken(result, "claimsToken", CacheRefreshReason.CLAIMS, cca.tokenCache.accessTokens.size());
}
//Asserts that there is one expected token in the cache, and that it was refreshed with the expected reason
private void assertRefreshedToken(IAuthenticationResult result, String expectedToken, CacheRefreshReason expectedReason, int cacheSize) {
assertEquals(1, cacheSize);
assertEquals(expectedToken, result.accessToken());
assertEquals(expectedReason, result.metadata().cacheRefreshReason());
}
// ========== SilentRequestHelper ==========
@Test
void getCacheRefreshReason_claimsPresent_returnsClaims() {
SilentParameters params = SilentParameters.builder(
Collections.singleton("scope"),
mock(IAccount.class))
.claims(new ClaimsRequest())
.build();
AuthenticationResult cachedResult = mock(AuthenticationResult.class);
when(cachedResult.accessToken()).thenReturn("valid-token");
when(cachedResult.expiresOn()).thenReturn(System.currentTimeMillis() / 1000 + 3600);
Logger log = mock(Logger.class);
assertEquals(CacheRefreshReason.CLAIMS,
SilentRequestHelper.getCacheRefreshReasonIfApplicable(params, cachedResult, log));
}
@Test
void getCacheRefreshReason_expiredToken_returnsExpired() {
SilentParameters params = SilentParameters.builder(
Collections.singleton("scope"),
mock(IAccount.class))
.build();
AuthenticationResult cachedResult = mock(AuthenticationResult.class);
when(cachedResult.accessToken()).thenReturn("expired-token");
when(cachedResult.expiresOn()).thenReturn(System.currentTimeMillis() / 1000 - 600);
Logger log = mock(Logger.class);
assertEquals(CacheRefreshReason.EXPIRED,
SilentRequestHelper.getCacheRefreshReasonIfApplicable(params, cachedResult, log));
}
@Test
void getCacheRefreshReason_proactiveRefresh_returnsProactiveRefresh() {
SilentParameters params = SilentParameters.builder(
Collections.singleton("scope"),
mock(IAccount.class))
.build();
long now = System.currentTimeMillis() / 1000;
AuthenticationResult cachedResult = mock(AuthenticationResult.class);
when(cachedResult.accessToken()).thenReturn("valid-token");
when(cachedResult.expiresOn()).thenReturn(now + 3600);
when(cachedResult.refreshOn()).thenReturn(now - 600);
Logger log = mock(Logger.class);
assertEquals(CacheRefreshReason.PROACTIVE_REFRESH,
SilentRequestHelper.getCacheRefreshReasonIfApplicable(params, cachedResult, log));
}
@Test
void getCacheRefreshReason_noAccessTokenWithRefreshToken_returnsNoCachedAccessToken() {
SilentParameters params = SilentParameters.builder(
Collections.singleton("scope"),
mock(IAccount.class))
.build();
AuthenticationResult cachedResult = mock(AuthenticationResult.class);
when(cachedResult.accessToken()).thenReturn(null);
when(cachedResult.refreshToken()).thenReturn("refresh-token-value");
Logger log = mock(Logger.class);
assertEquals(CacheRefreshReason.NO_CACHED_ACCESS_TOKEN,
SilentRequestHelper.getCacheRefreshReasonIfApplicable(params, cachedResult, log));
}
@Test
void getCacheRefreshReason_validToken_returnsNotApplicable() {
SilentParameters params = SilentParameters.builder(
Collections.singleton("scope"),
mock(IAccount.class))
.build();
long now = System.currentTimeMillis() / 1000;
AuthenticationResult cachedResult = mock(AuthenticationResult.class);
when(cachedResult.accessToken()).thenReturn("valid-token");
when(cachedResult.expiresOn()).thenReturn(now + 3600);
when(cachedResult.refreshOn()).thenReturn(null);
Logger log = mock(Logger.class);
assertEquals(CacheRefreshReason.NOT_APPLICABLE,
SilentRequestHelper.getCacheRefreshReasonIfApplicable(params, cachedResult, log));
}
}