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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class AuthenticationTests : IDisposable
{
private const string Basic = "Basic";
private const string TestUser = "testuser";
private const string TestPassword = "testpassword";
private HttpListenerFactory _factory;
private HttpListener _listener;
public AuthenticationTests()
{
_factory = new HttpListenerFactory();
_listener = _factory.GetListener();
}
public void Dispose() => _factory.Dispose();
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // Managed implementation connects successfully.
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Basic")]
[InlineData("NTLM")]
[InlineData("Negotiate")]
[InlineData("Unknown")]
public async Task NoAuthentication_AuthenticationProvided_ReturnsForbiddenStatusCode(string headerType)
{
_listener.AuthenticationSchemes = AuthenticationSchemes.None;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(headerType, "body");
await AuthenticationFailure(client, HttpStatusCode.Forbidden);
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(AuthenticationSchemes.Basic)]
[InlineData(AuthenticationSchemes.Basic | AuthenticationSchemes.None)]
[InlineData(AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous)]
public async Task BasicAuthentication_ValidUsernameAndPassword_Success(AuthenticationSchemes authScheme)
{
_listener.AuthenticationSchemes = authScheme;
await ValidateValidUser();
}
[ActiveIssue(19967, TargetFrameworkMonikers.NetFramework)]
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(BasicAuthenticationHeader_TestData))]
public async Task BasicAuthentication_InvalidRequest_SendsStatusCodeClient(string header, HttpStatusCode statusCode)
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Basic, header);
HttpResponseMessage response = await AuthenticationFailure(client, statusCode);
if (statusCode == HttpStatusCode.Unauthorized)
{
Assert.Equal("Basic realm=\"\"", response.Headers.WwwAuthenticate.ToString());
}
else
{
Assert.Empty(response.Headers.WwwAuthenticate);
}
}
}
public static IEnumerable<object[]> BasicAuthenticationHeader_TestData()
{
yield return new object[] { string.Empty, HttpStatusCode.Unauthorized };
yield return new object[] { null, HttpStatusCode.Unauthorized };
yield return new object[] { Convert.ToBase64String(Encoding.ASCII.GetBytes("username")), HttpStatusCode.BadRequest };
yield return new object[] { "abc", HttpStatusCode.InternalServerError };
}
[ActiveIssue(19967, TargetFrameworkMonikers.NetFramework)]
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20098, TestPlatforms.Unix)]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("ExampleRealm")]
[InlineData(" ExampleRealm ")]
[InlineData("")]
[InlineData(null)]
public async Task BasicAuthentication_RealmSet_SendsChallengeToClient(string realm)
{
_listener.Realm = realm;
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
Assert.Equal(realm, _listener.Realm);
using (var client = new HttpClient())
{
HttpResponseMessage response = await AuthenticationFailure(client, HttpStatusCode.Unauthorized);
Assert.Equal($"Basic realm=\"{realm}\"", response.Headers.WwwAuthenticate.ToString());
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestAnonymousAuthentication()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
await ValidateNullUser();
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestBasicAuthenticationWithDelegate()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.None;
AuthenticationSchemeSelector selector = new AuthenticationSchemeSelector(SelectAnonymousAndBasicSchemes);
_listener.AuthenticationSchemeSelectorDelegate += selector;
await ValidateValidUser();
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("somename:somepassword", "somename", "somepassword")]
[InlineData("somename:", "somename", "")]
[InlineData(":somepassword", "", "somepassword")]
[InlineData("somedomain\\somename:somepassword", "somedomain\\somename", "somepassword")]
[InlineData("\\somename:somepassword", "\\somename", "somepassword")]
public async Task TestBasicAuthenticationWithValidAuthStrings(string authString, string expectedName, string expectedPassword)
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
await ValidateValidUser(authString, expectedName, expectedPassword);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestAnonymousAuthenticationWithDelegate()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.None;
AuthenticationSchemeSelector selector = new AuthenticationSchemeSelector(SelectAnonymousScheme);
_listener.AuthenticationSchemeSelectorDelegate += selector;
await ValidateNullUser();
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support NTLM")]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
public async Task NtlmAuthentication_Conversation_ReturnsExpectedType2Message()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("NTLM", "TlRMTVNTUAABAAAABzIAAAYABgArAAAACwALACAAAABXT1JLU1RBVElPTkRPTUFJTg==");
HttpResponseMessage message = await AuthenticationFailure(client, HttpStatusCode.Unauthorized);
Assert.StartsWith("NTLM", message.Headers.WwwAuthenticate.ToString());
}
}
public static IEnumerable<object[]> InvalidNtlmNegotiateAuthentication_TestData()
{
yield return new object[] { null, HttpStatusCode.Unauthorized };
yield return new object[] { string.Empty, HttpStatusCode.Unauthorized };
yield return new object[] { "abc", HttpStatusCode.BadRequest };
yield return new object[] { "abcd", HttpStatusCode.BadRequest };
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support NTLM")]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
[MemberData(nameof(InvalidNtlmNegotiateAuthentication_TestData))]
public async Task NtlmAuthentication_InvalidRequestHeaders_ReturnsExpectedStatusCode(string header, HttpStatusCode statusCode)
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("NTLM", header);
HttpResponseMessage message = await AuthenticationFailure(client, statusCode);
if (statusCode == HttpStatusCode.Unauthorized)
{
Assert.Equal("NTLM", message.Headers.WwwAuthenticate.ToString());
}
else
{
Assert.Empty(message.Headers.WwwAuthenticate);
}
}
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support Negotiate")]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
public async Task NegotiateAuthentication_Conversation_ReturnsExpectedType2Message()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Negotiate", "TlRMTVNTUAABAAAABzIAAAYABgArAAAACwALACAAAABXT1JLU1RBVElPTkRPTUFJTg==");
HttpResponseMessage message = await AuthenticationFailure(client, HttpStatusCode.Unauthorized);
Assert.StartsWith("Negotiate", message.Headers.WwwAuthenticate.ToString());
}
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support Negotiate")]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
[MemberData(nameof(InvalidNtlmNegotiateAuthentication_TestData))]
public async Task NegotiateAuthentication_InvalidRequestHeaders_ReturnsExpectedStatusCode(string header, HttpStatusCode statusCode)
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Negotiate", header);
HttpResponseMessage message = await AuthenticationFailure(client, statusCode);
Assert.Empty(message.Headers.WwwAuthenticate);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AuthenticationSchemeSelectorDelegate_ReturnsInvalidAuthenticationScheme_PerformsNoAuthentication()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
_listener.AuthenticationSchemeSelectorDelegate = (request) => (AuthenticationSchemes)(-1);
using (var client = new HttpClient())
{
Task<HttpResponseMessage> clientTask = client.GetAsync(_factory.ListeningUrl);
HttpListenerContext context = await _listener.GetContextAsync();
Assert.False(context.Request.IsAuthenticated);
context.Response.Close();
await clientTask;
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AuthenticationSchemeSelectorDelegate_ThrowsException_SendsInternalServerErrorToClient()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
_listener.AuthenticationSchemeSelectorDelegate = (request) => { throw new InvalidOperationException(); };
using (var client = new HttpClient())
{
HttpResponseMessage response = await AuthenticationFailure(client, HttpStatusCode.InternalServerError);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemeSelectorDelegate_ThrowsOutOfMemoryException_RethrowsException()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
_listener.AuthenticationSchemeSelectorDelegate = (request) => { throw new OutOfMemoryException(); };
using (var client = new HttpClient())
{
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
Assert.Throws<OutOfMemoryException>(() => _listener.GetContext());
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemeSelectorDelegate_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.AuthenticationSchemeSelectorDelegate = null);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemes_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.AuthenticationSchemes = AuthenticationSchemes.Basic);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetNull_ThrowsArgumentNullException()
{
using (var listener = new HttpListener())
{
AssertExtensions.Throws<ArgumentNullException>("value", () => listener.ExtendedProtectionPolicy = null);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.ExtendedProtectionPolicy = null);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetCustomChannelBinding_ThrowsObjectDisposedException()
{
using (var listener = new HttpListener())
{
var protectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Always, new CustomChannelBinding());
AssertExtensions.Throws<ArgumentException>("value", "CustomChannelBinding", () => listener.ExtendedProtectionPolicy = protectionPolicy);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void UnsafeConnectionNtlmAuthentication_SetGet_ReturnsExpected()
{
using (var listener = new HttpListener())
{
Assert.Equal(false, listener.UnsafeConnectionNtlmAuthentication);
listener.UnsafeConnectionNtlmAuthentication = true;
Assert.True(listener.UnsafeConnectionNtlmAuthentication);
listener.UnsafeConnectionNtlmAuthentication = false;
Assert.False(listener.UnsafeConnectionNtlmAuthentication);
listener.UnsafeConnectionNtlmAuthentication = false;
Assert.False(listener.UnsafeConnectionNtlmAuthentication);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void UnsafeConnectionNtlmAuthentication_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.UnsafeConnectionNtlmAuthentication = false);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionSelectorDelegate_SetNull_ThrowsArgumentNullException()
{
using (var listener = new HttpListener())
{
AssertExtensions.Throws<ArgumentNullException>("value", null, () => listener.ExtendedProtectionSelectorDelegate = null);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionSelectorDelegate_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.ExtendedProtectionSelectorDelegate = null);
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Realm_SetWithoutBasicAuthenticationScheme_SendsNoChallengeToClient()
{
_listener.Realm = "ExampleRealm";
using (HttpClient client = new HttpClient())
{
Task<HttpResponseMessage> clientTask = client.GetAsync(_factory.ListeningUrl);
HttpListenerContext context = await _listener.GetContextAsync();
context.Response.Close();
HttpResponseMessage response = await clientTask;
Assert.Empty(response.Headers.WwwAuthenticate);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Realm_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
listener.Close();
Assert.Throws<ObjectDisposedException>(() => listener.Realm = null);
}
public async Task<HttpResponseMessage> AuthenticationFailure(HttpClient client, HttpStatusCode errorCode)
{
Task<HttpResponseMessage> clientTask = client.GetAsync(_factory.ListeningUrl);
// The server task will hang forever if it is not cancelled.
var tokenSource = new CancellationTokenSource();
Task<HttpListenerContext> serverTask = Task.Run(() => _listener.GetContext(), tokenSource.Token);
// The client task should complete first - the server should send a 401 response.
Task resultTask = await Task.WhenAny(clientTask, serverTask);
tokenSource.Cancel();
if (resultTask == serverTask)
{
await serverTask;
}
Assert.Same(clientTask, resultTask);
Assert.Equal(errorCode, clientTask.Result.StatusCode);
return clientTask.Result;
}
private async Task ValidateNullUser()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new Http.Headers.AuthenticationHeaderValue(
Basic,
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", TestUser, TestPassword))));
Task<string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext listenerContext = await serverContextTask;
Assert.Null(listenerContext.User);
}
}
private Task ValidateValidUser() =>
ValidateValidUser(string.Format("{0}:{1}", TestUser, TestPassword), TestUser, TestPassword);
private async Task ValidateValidUser(string authHeader, string expectedUsername, string expectedPassword)
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
Basic,
Convert.ToBase64String(Encoding.ASCII.GetBytes(authHeader)));
Task <string> clientTask = client.GetStringAsync(_factory.ListeningUrl);
HttpListenerContext listenerContext = await serverContextTask;
Assert.Equal(expectedUsername, listenerContext.User.Identity.Name);
Assert.Equal(!string.IsNullOrEmpty(expectedUsername), listenerContext.User.Identity.IsAuthenticated);
Assert.Equal(Basic, listenerContext.User.Identity.AuthenticationType);
HttpListenerBasicIdentity id = Assert.IsType<HttpListenerBasicIdentity>(listenerContext.User.Identity);
Assert.Equal(expectedPassword, id.Password);
}
}
private AuthenticationSchemes SelectAnonymousAndBasicSchemes(HttpListenerRequest request) => AuthenticationSchemes.Anonymous | AuthenticationSchemes.Basic;
private AuthenticationSchemes SelectAnonymousScheme(HttpListenerRequest request) => AuthenticationSchemes.Anonymous;
private class CustomChannelBinding : ChannelBinding
{
public override int Size => 0;
protected override bool ReleaseHandle() => true;
}
}
}
|