-
Notifications
You must be signed in to change notification settings - Fork 343
/
OboRequestTests.cs
371 lines (302 loc) · 19.9 KB
/
OboRequestTests.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Test.Common;
using Microsoft.Identity.Test.Common.Core.Helpers;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Identity.Test.Unit.RequestsTests
{
[TestClass]
public class OboRequestTests
{
[TestInitialize]
public void TestInitialize()
{
TestCommon.ResetInternalStaticCaches();
}
private MockHttpMessageHandler AddMockHandlerAadSuccess(
MockHttpManager httpManager,
string authority,
IList<string> unexpectedHeaders = null,
HttpResponseMessage responseMessage = null)
{
var handler = new MockHttpMessageHandler
{
ExpectedUrl = authority + "oauth2/v2.0/token",
ExpectedMethod = HttpMethod.Post,
ResponseMessage = responseMessage ?? MockHelpers.CreateSuccessTokenResponseMessage(),
UnexpectedRequestHeaders = unexpectedHeaders
};
httpManager.AddMockHandler(handler);
return handler;
}
[TestMethod]
public async Task AcquireTokenByObo_AccessTokenExpiredRefreshTokenAvailable_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
//Expire access tokens
TokenCacheHelper.ExpireAccessTokens(cca.UserTokenCacheInternal);
MockHttpMessageHandler mockTokenRequestHttpHandlerRefresh = AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
mockTokenRequestHttpHandlerRefresh.ExpectedPostData = new Dictionary<string, string> { { "grant_type", "refresh_token" } };
result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
}
}
[TestMethod]
public async Task AcquireTokenByObo_MissMatchUserAssertions_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
//Update user assertions
TokenCacheHelper.UpdateUserAssertions(cca);
MockHttpMessageHandler mockTokenRequestHttpHandlerRefresh = AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
//Access and refresh tokens have a different user assertion so MSAL should perform OBO.
result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
}
}
[TestMethod]
public async Task AcquireTokenByObo_AccessTokenInCache_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
var userCacheAccess = cca.UserTokenCache.RecordAccess();
UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
userCacheAccess.AssertAccessCounts(1, 1);
result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion).ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.Cache);
Assert.AreEqual("some-access-token", result.AccessToken);
userCacheAccess.AssertAccessCounts(2, 1);
MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single();
MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Single();
Assert.AreEqual(userAssertion.AssertionHash, cachedAccessToken.OboCacheKey);
Assert.AreEqual(userAssertion.AssertionHash, cachedRefreshToken.OboCacheKey);
}
}
[TestMethod]
public async Task AcquireTokenByObo_InLongRunningProcess_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
var userCacheAccess = cca.UserTokenCache.RecordAccess();
string oboCacheKey = "obo-cache-key";
var result = await cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstants.DefaultAccessToken, ref oboCacheKey)
.ExecuteAsync().ConfigureAwait(false);
// Token's not in cache, searched by user assertion hash, retrieved from IdP, saved with the provided OBO cache key
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single();
MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Single();
Assert.AreEqual(oboCacheKey, cachedAccessToken.OboCacheKey);
Assert.AreEqual(oboCacheKey, cachedRefreshToken.OboCacheKey);
userCacheAccess.AssertAccessCounts(1, 1);
result = await cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, oboCacheKey).ExecuteAsync().ConfigureAwait(false);
// Token is in the cache, retrieved by the provided OBO cache key
Assert.IsNotNull(result);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.Cache);
Assert.AreEqual("some-access-token", result.AccessToken);
userCacheAccess.AssertAccessCounts(2, 1);
}
}
[TestMethod]
public async Task AcquireTokenByObo_InitiateLongRunningProcessInWebApi_CacheKeyAlreadyExists_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
var userCacheAccess = cca.UserTokenCache.RecordAccess();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant,
responseMessage: MockHelpers.CreateSuccessTokenResponseMessage(
TestConstants.UniqueId,
TestConstants.DisplayableId,
TestConstants.s_scope.ToArray(),
accessToken: TestConstants.ATSecret,
refreshToken: TestConstants.RTSecret));
string oboCacheKey = "obo-cache-key";
var result = await cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstants.DefaultAccessToken, ref oboCacheKey)
.ExecuteAsync().ConfigureAwait(false);
// Cache is empty or token with the same scopes, OBO cache key, etc. not in cache -> AT and RT are retrieved from IdP and saved
Assert.IsNotNull(result);
Assert.AreEqual(TestConstants.ATSecret, result.AccessToken);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
MsalAccessTokenCacheItem cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Single();
MsalRefreshTokenCacheItem cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Single();
Assert.AreEqual(oboCacheKey, cachedAccessToken.OboCacheKey);
Assert.AreEqual(oboCacheKey, cachedRefreshToken.OboCacheKey);
Assert.AreEqual(TestConstants.RTSecret, cachedRefreshToken.Secret);
userCacheAccess.AssertAccessCounts(1, 1);
// Token with the same scopes, OBO cache key, etc. exists in the cache -> throw error
var exception = await AssertException.TaskThrowsAsync<MsalClientException>(
() => cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstants.DefaultAccessToken, ref oboCacheKey)
.ExecuteAsync())
.ConfigureAwait(false);
Assert.AreEqual(MsalError.OboCacheKeyAlreadyInCacheError, exception.ErrorCode);
userCacheAccess.AssertAccessCounts(2, 1);
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant,
responseMessage: MockHelpers.CreateSuccessTokenResponseMessage(
$"{TestConstants.UniqueId}2",
$"{TestConstants.DisplayableId}2",
new string[] { "differentscope" },
utid: TestConstants.Utid2,
accessToken: TestConstants.ATSecret2,
refreshToken: TestConstants.RTSecret2));
// Token with the same OBO cache key but different scopes, etc. exists in the cache -> save AT and RT in the cache since it's a different token
// This mirrors the current behavior with AcquireTokenOnBehalfOf - two different tokens with the same user assertion can exist in the cache
result = await cca.InitiateLongRunningProcessInWebApi(new string[] { "differentscope" }, $"{TestConstants.DefaultAccessToken}2", ref oboCacheKey)
.ExecuteAsync()
.ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual(TestConstants.ATSecret2, result.AccessToken);
Assert.AreEqual(result.AuthenticationResultMetadata.TokenSource, TokenSource.IdentityProvider);
cachedAccessToken = cca.UserTokenCacheInternal.Accessor.GetAllAccessTokens().FirstOrDefault(at => at.Secret.Equals(TestConstants.ATSecret2));
cachedRefreshToken = cca.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().FirstOrDefault(rt => rt.Secret.Equals(TestConstants.RTSecret2));
Assert.AreEqual(oboCacheKey, cachedAccessToken.OboCacheKey);
Assert.AreEqual(oboCacheKey, cachedRefreshToken.OboCacheKey);
Assert.AreEqual(TestConstants.RTSecret2, cachedRefreshToken.Secret);
userCacheAccess.AssertAccessCounts(3, 2);
}
}
[TestMethod]
public async Task AcquireTokenByObo_AcquireTokenInLongRunningProcess_CacheKeyDoesNotExist_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
var userCacheAccess = cca.UserTokenCache.RecordAccess();
string oboCacheKey = "obo-cache-key";
// If token with OBO cache key provided does not exist in the cache throw error
var exception = await AssertException.TaskThrowsAsync<MsalClientException>(
() => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope.ToArray(), oboCacheKey)
.ExecuteAsync())
.ConfigureAwait(false);
Assert.AreEqual(MsalError.OboCacheKeyNotInCacheError, exception.ErrorCode);
userCacheAccess.AssertAccessCounts(1, 0);
}
}
[TestMethod]
public async Task AcquireTokenByObo_InLongRunningProcess_WithNullCacheKey_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
string cacheKey = null;
await cca.InitiateLongRunningProcessInWebApi(TestConstants.s_scope, TestConstants.DefaultAccessToken, ref cacheKey)
.ExecuteAsync()
.ConfigureAwait(false);
// If not provided, cache key is defaulted to the assertion hash.
Assert.AreEqual(new UserAssertion(TestConstants.DefaultAccessToken).AssertionHash, cacheKey);
// Cache key is required in this method
await AssertException.TaskThrowsAsync<ArgumentNullException>(
() => cca.AcquireTokenInLongRunningProcess(TestConstants.s_scope, null)
.ExecuteAsync())
.ConfigureAwait(false);
}
}
[TestMethod]
public async Task AcquireTokenByObo_NullCcs_TestAsync()
{
using (var httpManager = new MockHttpManager())
{
httpManager.AddInstanceDiscoveryMockHandler();
var extraUnexpectedHeaders = new List<string>() { { Constants.CcsRoutingHintHeader } };
AddMockHandlerAadSuccess(httpManager, TestConstants.AuthorityCommonTenant, extraUnexpectedHeaders);
var cca = ConfidentialClientApplicationBuilder
.Create(TestConstants.ClientId)
.WithClientSecret(TestConstants.ClientSecret)
.WithAuthority(TestConstants.AuthorityCommonTenant)
.WithHttpManager(httpManager)
.BuildConcrete();
UserAssertion userAssertion = new UserAssertion(TestConstants.DefaultAccessToken);
var result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion)
.WithCcsRoutingHint("")
.WithCcsRoutingHint("", "")
.ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
result = await cca.AcquireTokenOnBehalfOf(TestConstants.s_scope, userAssertion)
.WithCcsRoutingHint("")
.WithCcsRoutingHint("", "")
.ExecuteAsync().ConfigureAwait(false);
Assert.IsNotNull(result);
Assert.AreEqual("some-access-token", result.AccessToken);
}
}
}
}