-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntrospection.cs
More file actions
429 lines (328 loc) · 15.7 KB
/
Introspection.cs
File metadata and controls
429 lines (328 loc) · 15.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
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
// Copyright (c) Duende Software. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Duende.IdentityModel;
using Duende.IdentityModel.Client;
using FluentAssertions;
using IdentityModel.AspNetCore.OAuth2Introspection;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Tests.Util;
using Xunit;
namespace Tests
{
public class Introspection
{
private static readonly string clientId = "client";
private static readonly string clientSecret = "secret";
private readonly Action<OAuth2IntrospectionOptions> _options = o =>
{
o.Authority = "https://authority.com";
o.DiscoveryPolicy.RequireKeySet = false;
o.ClientId = clientId;
o.ClientSecret = clientSecret;
};
[Fact]
public async Task Unauthorized_Client()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Unauthorized);
var client = PipelineFactory.CreateClient(o => _options(o), handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ActiveToken()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
var client = PipelineFactory.CreateClient(_options, handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
var request = handler.LastRequest;
request.Should().ContainKey("client_id").WhichValue.Should().Be(clientId);
request.Should().ContainKey("client_secret").WhichValue.Should().Be(clientSecret);
}
[Theory]
[InlineData(5000, "testAssertion1", "testAssertion1")]
[InlineData(-5000, "testAssertion1", "testAssertion2")]
public async Task ActiveToken_With_ClientAssertion(int ttl, string assertion1, string assertion2)
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
var count = 0;
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.ClientSecret = null;
o.Events.OnUpdateClientAssertion = e =>
{
count++;
e.ClientAssertion = new ClientAssertion
{
Type = "testType",
Value = "testAssertion" + count
};
e.ClientAssertionExpirationTime = DateTime.UtcNow.AddMilliseconds(ttl);
return Task.CompletedTask;
};
}, handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
var request = handler.LastRequest;
request.Should().ContainKey("client_id").WhichValue.Should().Be(clientId);
request.Should().ContainKey("client_assertion_type").WhichValue.Should().Be("testType");
request.Should().ContainKey("client_assertion").WhichValue.Should().Be(assertion1);
result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
request = handler.LastRequest;
request.Should().ContainKey("client_id").WhichValue.Should().Be(clientId);
request.Should().ContainKey("client_assertion_type").WhichValue.Should().Be("testType");
request.Should().ContainKey("client_assertion").WhichValue.Should().Be(assertion2);
}
[Fact]
public async Task Active_token_with_inline_event_events_should_be_called()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
bool? validatedCalled = null;
bool? failureCalled = null;
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.Events.OnTokenValidated = e =>
{
validatedCalled = true;
return Task.CompletedTask;
};
o.Events.OnAuthenticationFailed = e =>
{
failureCalled = true;
return Task.CompletedTask;
};
}, handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
validatedCalled.Should().BeTrue();
failureCalled.Should().BeNull();
}
[Fact]
public async Task ActiveToken_With_Caching_Ttl_Longer_Than_Duration()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active, TimeSpan.FromHours(1));
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.EnableCaching = true;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task ActiveToken_With_Caching_Ttl_Shorter_Than_Duration()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active, TimeSpan.FromMinutes(5));
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.EnableCaching = true;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task InactiveToken()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Inactive);
var client = PipelineFactory.CreateClient(o => _options(o), handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task InActive_token_with_inline_event_events_should_be_called()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Inactive);
bool? validatedCalled = null;
bool? failureCalled = null;
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.Events.OnTokenValidated = e =>
{
validatedCalled = true;
return Task.CompletedTask;
};
o.Events.OnAuthenticationFailed = e =>
{
failureCalled = true;
return Task.CompletedTask;
};
}, handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
validatedCalled.Should().BeNull();
failureCalled.Should().BeTrue();
}
[Fact]
public async Task ActiveToken_With_SavedToken()
{
var expectedToken = "expected_token";
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.SaveToken = true;
}, handler);
client.SetBearerToken(expectedToken);
var response = await client.GetAsync("http://test");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseDataStr = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseDataStr);
responseData.Should().Contain("token", expectedToken);
}
[Fact]
public async Task ActiveToken_With_SavedToken_And_Caching()
{
var expectedToken = "expected_token";
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active, TimeSpan.FromHours(1));
var server = PipelineFactory.CreateServer(o =>
{
_options(o);
o.SaveToken = true;
o.EnableCaching = true;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
var client = server.CreateClient();
client.SetBearerToken(expectedToken);
var firstResponse = await client.GetAsync("http://test");
firstResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var secondResponse = await client.GetAsync("http://test");
secondResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var responseDataStr = await secondResponse.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseDataStr);
responseData.Should().Contain("token", expectedToken);
AssertCacheItemExists(server, string.Empty, expectedToken);
}
[Fact]
public async Task ActiveToken_With_SavedToken_And_Caching_With_Cache_Key_Prefix()
{
var expectedToken = "expected_token";
var cacheKeyPrefix = "KeyPrefix";
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active, TimeSpan.FromHours(1));
var server = PipelineFactory.CreateServer(o =>
{
_options(o);
o.SaveToken = true;
o.EnableCaching = true;
o.CacheKeyPrefix = cacheKeyPrefix;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
var client = server.CreateClient();
client.SetBearerToken(expectedToken);
var firstResponse = await client.GetAsync("http://test");
firstResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var secondResponse = await client.GetAsync("http://test");
secondResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var responseDataStr = await secondResponse.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseDataStr);
responseData.Should().Contain("token", expectedToken);
AssertCacheItemExists(server, cacheKeyPrefix, expectedToken);
}
[Fact]
public async Task Repeated_active_token_with_caching_enabled_should_hit_cache()
{
var expectedToken = "expected_token";
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active, TimeSpan.FromHours(1));
var server = PipelineFactory.CreateServer(o =>
{
_options(o);
o.SaveToken = true;
o.EnableCaching = true;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
var client = server.CreateClient();
client.SetBearerToken(expectedToken);
var firstResponse = await client.GetAsync("http://test");
firstResponse.StatusCode.Should().Be(HttpStatusCode.OK);
handler.SentIntrospectionRequest.Should().BeTrue();
handler.SentIntrospectionRequest = false;
var secondResponse = await client.GetAsync("http://test");
handler.SentIntrospectionRequest.Should().BeFalse();
AssertCacheItemExists(server, string.Empty, expectedToken);
}
[Fact]
public async Task Repeated_inactive_token_with_caching_enabled_should_hit_cache()
{
var expectedToken = "expected_token";
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Inactive);
var server = PipelineFactory.CreateServer(o =>
{
_options(o);
o.SaveToken = true;
o.EnableCaching = true;
o.CacheDuration = TimeSpan.FromMinutes(10);
}, handler, true);
var client = server.CreateClient();
client.SetBearerToken(expectedToken);
var firstResponse = await client.GetAsync("http://test");
firstResponse.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
handler.SentIntrospectionRequest.Should().BeTrue();
handler.SentIntrospectionRequest = false;
var secondResponse = await client.GetAsync("http://test");
secondResponse.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
handler.SentIntrospectionRequest.Should().BeFalse();
AssertCacheItemExists(server, string.Empty, expectedToken);
}
[Fact]
public async Task ActiveToken_With_Discovery_Unavailable_On_First_Request()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
var client = PipelineFactory.CreateClient(o => _options(o), handler);
client.SetBearerToken("sometoken");
handler.IsDiscoveryFailureTest = true;
await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.GetAsync("http://test"));
handler.IsDiscoveryFailureTest = false;
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task ActiveToken_RequestSending_AdditionalParameter_with_inline_event()
{
var handler = new IntrospectionEndpointHandler(IntrospectionEndpointHandler.Behavior.Active);
var client = PipelineFactory.CreateClient(o =>
{
_options(o);
o.Events.OnSendingRequest = e =>
{
e.TokenIntrospectionRequest.Parameters = Parameters.FromObject(new { additionalParameter = "42" });
return Task.CompletedTask;
};
}, handler);
client.SetBearerToken("sometoken");
var result = await client.GetAsync("http://test");
result.StatusCode.Should().Be(HttpStatusCode.OK);
handler.LastRequest.Should().Contain(new KeyValuePair<string, string>("additionalParameter", "42"));
}
private void AssertCacheItemExists(TestServer testServer, string cacheKeyPrefix, string token)
{
var cache = testServer.Services.GetService<IDistributedCache>();
var cacheItem = cache.GetString($"{cacheKeyPrefix}{token.ToSha256()}");
cacheItem.Should().NotBeNullOrEmpty();
}
}
}