-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathAcquireTokenSilentIT.java
More file actions
377 lines (299 loc) · 17.7 KB
/
AcquireTokenSilentIT.java
File metadata and controls
377 lines (299 loc) · 17.7 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.aad.msal4j;
import com.microsoft.aad.msal4j.labapi.*;
import static com.microsoft.aad.msal4j.labapi.KeyVaultSecrets.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
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 {
@Test
void acquireTokenSilent_OrganizationAuthority_TokenRefreshed() throws Exception {
// 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, TestConstants.GRAPH_DEFAULT_SCOPE, false);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
}
@Test
void acquireTokenSilent_LabAuthority_TokenNotRefreshed() throws Exception {
// Access token should be returned from cache, and not using refresh token
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, TestConstants.GRAPH_DEFAULT_SCOPE);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult acquireSilentResult = acquireTokenSilently(pca, account, TestConstants.GRAPH_DEFAULT_SCOPE, false);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(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());
}
@Test
void acquireTokenSilent_ForceRefresh() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, TestConstants.GRAPH_DEFAULT_SCOPE);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult resultAfterRefresh = acquireTokenSilently(pca, account, TestConstants.GRAPH_DEFAULT_SCOPE, true);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(resultAfterRefresh);
// Check that new refresh and id tokens are being returned
IntegrationTestHelper.assertTokensAreNotEqual(result, resultAfterRefresh);
assertEquals(TokenSource.IDENTITY_PROVIDER, result.metadata().tokenSource());
assertEquals(TokenSource.IDENTITY_PROVIDER, resultAfterRefresh.metadata().tokenSource());
}
@Test
void acquireTokenSilent_usingOrganizationsAuthority_returnCachedAt() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
acquireTokenSilent_returnCachedTokens(app.getAppId(), TestConstants.ORGANIZATIONS_AUTHORITY, user);
}
@Test
void acquireTokenSilent_usingTenantSpecificAuthority_returnCachedAt() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
acquireTokenSilent_returnCachedTokens(app.getAppId(), TestConstants.MICROSOFT_AUTHORITY_HOST + user.getTenantId(), user);
}
@Test
void acquireTokenSilent_ConfidentialClient_acquireTokenSilent() throws Exception {
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(TestConstants.GRAPH_DEFAULT_SCOPE))
.extraQueryParameters(extraParameters)
.build())
.get();
IntegrationTestHelper.assertAccessTokenNotNull(result);
String cachedAt = result.accessToken();
result = cca.acquireTokenSilently(SilentParameters
.builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE))
.extraQueryParameters(extraParameters)
.build())
.get();
assertNotNull(result);
assertEquals(result.accessToken(), cachedAt);
}
@Test
void acquireTokenSilent_ConfidentialClient_acquireTokenSilentDifferentScopeThrowsException()
throws Exception {
IConfidentialClientApplication cca = getConfidentialClientApplications();
IAuthenticationResult result = cca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(KEYVAULT_DEFAULT_SCOPE))
.build())
.get();
IntegrationTestHelper.assertAccessTokenNotNull(result);
//Acquiring token for different scope, expect exception to be thrown
assertThrows(ExecutionException.class, () -> cca.acquireTokenSilently(SilentParameters
.builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE))
.build())
.get());
}
@Test
void acquireTokenSilent_WithRefreshOn() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult resultOriginal = acquireTokenUsernamePassword(user, pca, TestConstants.GRAPH_DEFAULT_SCOPE);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(resultOriginal);
IAuthenticationResult resultSilent = acquireTokenSilently(pca, resultOriginal.account(), TestConstants.GRAPH_DEFAULT_SCOPE, false);
assertNotNull(resultSilent);
IntegrationTestHelper.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(), TestConstants.GRAPH_DEFAULT_SCOPE, 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));
IntegrationTestHelper.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(), TestConstants.GRAPH_DEFAULT_SCOPE, false);
//Current time is after refreshOn, so token should be refreshed
assertNotNull(resultSilentWithRefreshOn);
IntegrationTestHelper.assertTokensAreNotEqual(resultSilent, resultSilentWithRefreshOn);
assertEquals(TokenSource.CACHE, resultSilent.metadata().tokenSource());
assertEquals(TokenSource.IDENTITY_PROVIDER, resultSilentWithRefreshOn.metadata().tokenSource());
}
@Test
void acquireTokenSilent_TenantAsParameter() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters.
builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE),
user.getUpn(),
user.getPassword().toCharArray())
.build()).get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = acquireTokenSilently(pca, account, TestConstants.GRAPH_DEFAULT_SCOPE, false);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(silentResult);
IntegrationTestHelper.assertTokensAreEqual(result, silentResult);
IAuthenticationResult resultWithTenantParam = pca.acquireTokenSilently(SilentParameters.
builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE), account).
tenant(user.getTenantId()).
build()).get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(resultWithTenantParam);
IntegrationTestHelper.assertTokensAreNotEqual(result, resultWithTenantParam);
}
@Test
void acquireTokenSilent_emptyStringScope() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
String emptyScope = StringHelper.EMPTY_STRING;
IAuthenticationResult result = acquireTokenUsernamePassword(user, pca, emptyScope);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = acquireTokenSilently(pca, account, emptyScope, false);
IntegrationTestHelper.assertAccessAndIdTokensNotNull(silentResult);
assertEquals(result.accessToken(), silentResult.accessToken());
}
@Test
void acquireTokenSilent_emptyScopeSet() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
Set<String> scopes = new HashSet<>();
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters.
builder(scopes,
user.getUpn(),
user.getPassword().toCharArray())
.build())
.get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
IAccount account = pca.getAccounts().join().iterator().next();
IAuthenticationResult silentResult = pca.acquireTokenSilently(SilentParameters.
builder(scopes, account)
.build())
.get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(silentResult);
assertEquals(result.accessToken(), silentResult.accessToken());
}
@Test
public void acquireTokenSilent_ClaimsForceRefresh() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
Set<String> scopes = new HashSet<>();
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters.
builder(scopes,
user.getUpn(),
user.getPassword().toCharArray())
.build())
.get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(result);
IAuthenticationResult silentResultWithoutClaims = pca.acquireTokenSilently(SilentParameters.
builder(scopes, result.account())
.build())
.get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(silentResultWithoutClaims);
assertEquals(result.accessToken(), silentResultWithoutClaims.accessToken());
//If claims are added to a silent request, it should trigger the refresh flow and return a new token
ClaimsRequest cr = new ClaimsRequest();
cr.requestClaimInAccessToken("email", null);
IAuthenticationResult silentResultWithClaims = pca.acquireTokenSilently(SilentParameters.
builder(scopes, result.account())
.claims(cr)
.build())
.get();
IntegrationTestHelper.assertAccessAndIdTokensNotNull(silentResultWithClaims);
assertNotEquals(result.accessToken(), silentResultWithClaims.accessToken());
}
private IConfidentialClientApplication getConfidentialClientApplications() throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_WEBAPI);
String password = KeyVaultRegistry.getMsalTeamProvider().getSecretByName(app.getClientSecret()).getValue();
IClientCredential credential = ClientCredentialFactory.createFromSecret(password);
return ConfidentialClientApplication.builder(
app.getAppId(), credential).
authority(TestConstants.AUTHORITY_PUBLIC_TENANT_SPECIFIC).
build();
}
private void acquireTokenSilent_returnCachedTokens(String appId, String authority, UserConfig user) throws Exception {
PublicClientApplication pca = PublicClientApplication.builder(
appId).
authority(authority).
build();
IAuthenticationResult interactiveAuthResult = acquireTokenUsernamePassword(user, pca, TestConstants.GRAPH_DEFAULT_SCOPE);
assertNotNull(interactiveAuthResult);
IAuthenticationResult silentAuthResult = pca.acquireTokenSilently(
SilentParameters.builder(
Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE), interactiveAuthResult.account())
.build())
.get();
assertNotNull(silentAuthResult);
assertEquals(interactiveAuthResult.accessToken(), silentAuthResult.accessToken());
}
private IPublicClientApplication getPublicClientApplicationWithTokensInCache()
throws Exception {
AppConfig app = LabResponseHelper.getAppConfig(APP_PCACLIENT);
UserConfig user = LabResponseHelper.getUserConfig(USER_PUBLIC_CLOUD);
PublicClientApplication pca = PublicClientApplication.builder(
app.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
acquireTokenUsernamePassword(user, pca, TestConstants.GRAPH_DEFAULT_SCOPE);
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(UserConfig 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();
}
}