-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathAcquireTokenSilentlyTest.java
More file actions
200 lines (141 loc) · 10.5 KB
/
AcquireTokenSilentlyTest.java
File metadata and controls
200 lines (141 loc) · 10.5 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
// 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.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
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;
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());
}
}