-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathAcquireTokenSilentIT.java
430 lines (337 loc) · 18.8 KB
/
AcquireTokenSilentIT.java
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.aad.msal4j;
import labapi.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.api.BeforeAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.net.MalformedURLException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import static com.microsoft.aad.msal4j.TestConstants.KEYVAULT_DEFAULT_SCOPE;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AcquireTokenSilentIT {
private LabUserProvider labUserProvider;
private Config cfg;
@BeforeAll
void setUp() {
labUserProvider = LabUserProvider.getInstance();
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_OrganizationAuthority_TokenRefreshed(String environment) throws Exception {
cfg = new Config(environment);
// When using common, organization, or consumer tenants, cache has no way
// of determining which access token to return therefore token is always refreshed
IPublicClientApplication pca = getPublicClientApplicationWithTokensInCache();
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult result = acquireTokenSilently(pca, account, cfg.graphDefaultScope(), false);
assertResultNotNull(result);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_LabAuthority_TokenNotRefreshed(String environment) throws Exception {
cfg = new Config(environment);
// Access token should be returned from cache, and not using refresh token
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult acquireSilentResult = acquireTokenSilently(pca, account, cfg.graphDefaultScope(), false);
assertResultNotNull(result);
// Check that access and id tokens are coming from cache
assertEquals(result.accessToken(), acquireSilentResult.accessToken());
assertEquals(result.idToken(), acquireSilentResult.idToken());
assertEquals(TokenSource.IDENTITY_PROVIDER, result.metadata().tokenSource());
assertEquals(TokenSource.CACHE, acquireSilentResult.metadata().tokenSource());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_ForceRefresh(String environment) throws Exception {
cfg = new Config(environment);
User user = labUserProvider.getDefaultUser(environment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
assertResultNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult resultAfterRefresh = acquireTokenSilently(pca, account, cfg.graphDefaultScope(), true);
assertResultNotNull(resultAfterRefresh);
// Check that new refresh and id tokens are being returned
assertTokensAreNotEqual(result, resultAfterRefresh);
assertEquals(TokenSource.IDENTITY_PROVIDER, result.metadata().tokenSource());
assertEquals(TokenSource.IDENTITY_PROVIDER, resultAfterRefresh.metadata().tokenSource());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_MultipleAccountsInCache_UseCorrectAccount(String environment) throws Exception {
cfg = new Config(environment);
IPublicClientApplication pca = getPublicClientApplicationWithTokensInCache();
// get lab user for different account
User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_4);
// acquire token for different account
acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
Set<IAccount> accounts = pca.getAccounts().join();
IAccount account = accounts.stream().filter(
x -> x.username().equalsIgnoreCase(
user.getUpn())).findFirst().orElse(null);
IAuthenticationResult result = acquireTokenSilently(pca, account, cfg.graphDefaultScope(), false);
assertResultNotNull(result);
assertEquals(result.account().username(), user.getUpn());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_ADFS2019(String environment) throws Exception {
cfg = new Config(environment);
UserQueryParameters query = new UserQueryParameters();
query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment);
query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019);
query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED);
User user = labUserProvider.getLabUser(query);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
assertResultNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult acquireSilentResult = acquireTokenSilently(pca, account, TestConstants.ADFS_SCOPE, false);
assertResultNotNull(acquireSilentResult);
account = pca.getAccounts().join().iterator().next();
IAuthenticationResult resultAfterRefresh = acquireTokenSilently(pca, account, TestConstants.ADFS_SCOPE, true);
assertResultNotNull(resultAfterRefresh);
assertTokensAreNotEqual(result, resultAfterRefresh);
}
@Test
void acquireTokenSilent_usingCommonAuthority_returnCachedAt() throws Exception {
acquireTokenSilent_returnCachedTokens(cfg.organizationsAuthority());
}
@Test
void acquireTokenSilent_usingTenantSpecificAuthority_returnCachedAt() throws Exception {
acquireTokenSilent_returnCachedTokens(cfg.tenantSpecificAuthority());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_ConfidentialClient_acquireTokenSilent(String environment) throws Exception {
cfg = new Config(environment);
IConfidentialClientApplication cca = getConfidentialClientApplications();
//test that adding extra query parameters does not break the flow
Map<String, String> extraParameters = new HashMap<>();
extraParameters.put("test","test");
IAuthenticationResult result = cca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(cfg.graphDefaultScope()))
.extraQueryParameters(extraParameters)
.build())
.get();
assertNotNull(result);
assertNotNull(result.accessToken());
String cachedAt = result.accessToken();
result = cca.acquireTokenSilently(SilentParameters
.builder(Collections.singleton(cfg.graphDefaultScope()))
.extraQueryParameters(extraParameters)
.build())
.get();
assertNotNull(result);
assertEquals(result.accessToken(), cachedAt);
}
@Test
public void acquireTokenSilent_ConfidentialClient_acquireTokenSilentDifferentScopeThrowsException()
throws Exception {
cfg = new Config(AzureEnvironment.AZURE);
IConfidentialClientApplication cca = getConfidentialClientApplications();
IAuthenticationResult result = cca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(KEYVAULT_DEFAULT_SCOPE))
.build())
.get();
assertNotNull(result);
assertNotNull(result.accessToken());
//Acquiring token for different scope, expect exception to be thrown
assertThrows(ExecutionException.class, () -> cca.acquireTokenSilently(SilentParameters
.builder(Collections.singleton(cfg.graphDefaultScope()))
.build())
.get());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_WithRefreshOn(String environment) throws Exception {
cfg = new Config(environment);
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult resultOriginal = acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
assertResultNotNull(resultOriginal);
IAuthenticationResult resultSilent = acquireTokenSilently(pca, resultOriginal.account(), cfg.graphDefaultScope(), false);
assertNotNull(resultSilent);
assertTokensAreEqual(resultOriginal, resultSilent);
//When this test was made, token responses did not contain the refresh_in field needed for an end-to-end test.
//In order to test silent flow behavior as though the service returned refresh_in, we manually change a cached
// token's refreshOn value from 0 (default if refresh_in missing) to a minute before/after the current time
String key = pca.tokenCache.accessTokens.keySet().iterator().next();
AccessTokenCacheEntity token = pca.tokenCache.accessTokens.get(key);
long currTimestampSec = new Date().getTime() / 1000;
token.refreshOn(Long.toString(currTimestampSec + 60));
pca.tokenCache.accessTokens.put(key, token);
IAuthenticationResult resultSilentWithRefreshOn = acquireTokenSilently(pca, resultOriginal.account(), cfg.graphDefaultScope(), false);
//Current time is before refreshOn, so token should not have been refreshed
assertNotNull(resultSilentWithRefreshOn);
assertEquals(pca.tokenCache.accessTokens.get(key).refreshOn(), Long.toString(currTimestampSec + 60));
assertTokensAreEqual(resultSilent, resultSilentWithRefreshOn);
token = pca.tokenCache.accessTokens.get(key);
token.refreshOn(Long.toString(currTimestampSec - 60));
pca.tokenCache.accessTokens.put(key, token);
resultSilentWithRefreshOn = acquireTokenSilently(pca, resultOriginal.account(), cfg.graphDefaultScope(), false);
//Current time is after refreshOn, so token should be refreshed
assertNotNull(resultSilentWithRefreshOn);
assertTokensAreNotEqual(resultSilent, resultSilentWithRefreshOn);
assertEquals(TokenSource.CACHE, resultSilent.metadata().tokenSource());
assertEquals(TokenSource.IDENTITY_PROVIDER, resultSilentWithRefreshOn.metadata().tokenSource());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_TenantAsParameter(String environment) throws Exception {
cfg = new Config(environment);
User user = labUserProvider.getDefaultUser(environment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters.
builder(Collections.singleton(cfg.graphDefaultScope()),
user.getUpn(),
user.getPassword().toCharArray())
.build()).get();
assertResultNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = acquireTokenSilently(pca, account, cfg.graphDefaultScope(), false);
assertResultNotNull(silentResult);
assertTokensAreEqual(result, silentResult);
IAuthenticationResult resultWithTenantParam = pca.acquireTokenSilently(SilentParameters.
builder(Collections.singleton(cfg.graphDefaultScope()), account).
tenant(cfg.tenant()).
build()).get();
assertResultNotNull(resultWithTenantParam);
assertTokensAreNotEqual(result, resultWithTenantParam);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_emptyStringScope(String environment) throws Exception {
cfg = new Config(environment);
User user = labUserProvider.getDefaultUser(environment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
String emptyScope = StringHelper.EMPTY_STRING;
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, emptyScope);
assertResultNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = acquireTokenSilently(pca, account, emptyScope, false);
assertResultNotNull(silentResult);
assertEquals(result.accessToken(), silentResult.accessToken());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.EnvironmentsProvider#createData")
void acquireTokenSilent_emptyScopeSet(String environment) throws Exception {
cfg = new Config(environment);
User user = labUserProvider.getDefaultUser(environment);
Set<String> scopes = new HashSet<>();
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters.
builder(scopes,
user.getUpn(),
user.getPassword().toCharArray())
.build())
.get();
assertResultNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = pca.acquireTokenSilently(SilentParameters.
builder(scopes, account)
.build())
.get();
assertResultNotNull(silentResult);
assertEquals(result.accessToken(), silentResult.accessToken());
}
private IConfidentialClientApplication getConfidentialClientApplications() throws Exception {
String clientId = cfg.appProvider.getOboAppId();
String password = cfg.appProvider.getOboAppPassword();
IClientCredential credential = ClientCredentialFactory.createFromSecret(password);
return ConfidentialClientApplication.builder(
clientId, credential).
//authority(MICROSOFT_AUTHORITY)
authority(cfg.tenantSpecificAuthority()).
build();
}
private void acquireTokenSilent_returnCachedTokens(String authority) throws Exception {
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(authority).
build();
IAuthenticationResult interactiveAuthResult = acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
assertNotNull(interactiveAuthResult);
IAuthenticationResult silentAuthResult = pca.acquireTokenSilently(
SilentParameters.builder(
Collections.singleton(cfg.graphDefaultScope()), interactiveAuthResult.account())
.build())
.get();
assertNotNull(silentAuthResult);
assertEquals(interactiveAuthResult.accessToken(), silentAuthResult.accessToken());
}
private IPublicClientApplication getPublicClientApplicationWithTokensInCache()
throws Exception {
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);
PublicClientApplication pca = PublicClientApplication.builder(
user.getAppId()).
authority(cfg.organizationsAuthority()).
build();
acquireTokenUsernamePassword(user, pca, cfg.graphDefaultScope());
return pca;
}
private IAuthenticationResult acquireTokenSilently(IPublicClientApplication pca, IAccount account, String scope, Boolean forceRefresh) throws InterruptedException, ExecutionException, MalformedURLException {
return pca.acquireTokenSilently(SilentParameters.
builder(Collections.singleton(scope), account).
forceRefresh(forceRefresh).
build())
.get();
}
private IAuthenticationResult acquireTokenUsernamePassword(User user, IPublicClientApplication pca, String scope) throws InterruptedException, ExecutionException {
Map<String, String> map = new HashMap<>();
map.put("test","test");
return pca.acquireToken(UserNamePasswordParameters.
builder(Collections.singleton(scope),
user.getUpn(),
user.getPassword().toCharArray())
.extraQueryParameters(map)
.build())
.get();
}
private void assertResultNotNull(IAuthenticationResult result) {
assertNotNull(result);
assertNotNull(result.accessToken());
assertNotNull(result.idToken());
}
private void assertTokensAreNotEqual(IAuthenticationResult result, IAuthenticationResult secondResult) {
assertNotEquals(result.accessToken(), secondResult.accessToken());
assertNotEquals(result.idToken(), secondResult.idToken());
}
private void assertTokensAreEqual(IAuthenticationResult result, IAuthenticationResult secondResult) {
assertEquals(result.accessToken(), secondResult.accessToken());
assertEquals(result.idToken(), secondResult.idToken());
}
}