This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 598
/
JwtBearerMiddlewareTests.cs
655 lines (573 loc) · 28.3 KB
/
JwtBearerMiddlewareTests.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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.JwtBearer
{
public class JwtBearerMiddlewareTests
{
[ConditionalFact(Skip = "Need to remove dependency on AAD since the generated tokens will expire")]
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
// https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/179
public async Task BearerTokenValidation()
{
var options = new JwtBearerOptions
{
Authority = "https://login.windows.net/tushartest.onmicrosoft.com",
Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"
};
options.TokenValidationParameters.ValidateLifetime = false;
var server = CreateServer(options);
var newBearerToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJodHRwczovL1R1c2hhclRlc3Qub25taWNyb3NvZnQuY29tL1RvZG9MaXN0U2VydmljZS1NYW51YWxKd3QiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9hZmJlY2UwMy1hZWFhLTRmM2YtODVlNy1jZTA4ZGQyMGNlNTAvIiwiaWF0IjoxNDE4MzMwNjE0LCJuYmYiOjE0MTgzMzA2MTQsImV4cCI6MTQxODMzNDUxNCwidmVyIjoiMS4wIiwidGlkIjoiYWZiZWNlMDMtYWVhYS00ZjNmLTg1ZTctY2UwOGRkMjBjZTUwIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI1Mzk3OTdjMi00MDE5LTQ2NTktOWRiNS03MmM0Yzc3NzhhMzMiLCJ1cG4iOiJWaWN0b3JAVHVzaGFyVGVzdC5vbm1pY3Jvc29mdC5jb20iLCJ1bmlxdWVfbmFtZSI6IlZpY3RvckBUdXNoYXJUZXN0Lm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IkQyMm9aMW9VTzEzTUFiQXZrdnFyd2REVE80WXZJdjlzMV9GNWlVOVUwYnciLCJmYW1pbHlfbmFtZSI6Ikd1cHRhIiwiZ2l2ZW5fbmFtZSI6IlZpY3RvciIsImFwcGlkIjoiNjEzYjVhZjgtZjJjMy00MWI2LWExZGMtNDE2Yzk3ODAzMGI3IiwiYXBwaWRhY3IiOiIwIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwiYWNyIjoiMSJ9.N_Kw1EhoVGrHbE6hOcm7ERdZ7paBQiNdObvp2c6T6n5CE8p0fZqmUd-ya_EqwElcD6SiKSiP7gj0gpNUnOJcBl_H2X8GseaeeMxBrZdsnDL8qecc6_ygHruwlPltnLTdka67s1Ow4fDSHaqhVTEk6lzGmNEcbNAyb0CxQxU6o7Fh0yHRiWoLsT8yqYk8nKzsHXfZBNby4aRo3_hXaa4i0SZLYfDGGYPdttG4vT_u54QGGd4Wzbonv2gjDlllOVGOwoJS6kfl1h8mk0qxdiIaT_ChbDWgkWvTB7bTvBE-EgHgV0XmAo0WtJeSxgjsG3KhhEPsONmqrSjhIUV4IVnF2w";
var response = await SendAsync(server, "http://example.com/oauth", newBearerToken);
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
}
[Fact]
public async Task SignInThrows()
{
var server = CreateServer(new JwtBearerOptions());
var transaction = await server.SendAsync("https://example.com/signIn");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task SignOutThrows()
{
var server = CreateServer(new JwtBearerOptions());
var transaction = await server.SendAsync("https://example.com/signOut");
Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
}
[Fact]
public async Task CustomHeaderReceived()
{
var server = CreateServer(new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, "Bob le Magnifique"),
new Claim(ClaimTypes.Email, "bob@contoso.com"),
new Claim(ClaimsIdentity.DefaultNameClaimType, "bob")
};
context.Ticket = new AuthenticationTicket(
new ClaimsPrincipal(new ClaimsIdentity(claims, context.Options.AuthenticationScheme)),
new AuthenticationProperties(), context.Options.AuthenticationScheme);
context.HandleResponse();
return Task.FromResult<object>(null);
}
}
});
var response = await SendAsync(server, "http://example.com/oauth", "someHeader someblob");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal("Bob le Magnifique", response.ResponseText);
}
[Fact]
public async Task NoHeaderReceived()
{
var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
}
[Fact]
public async Task HeaderWithoutBearerReceived()
{
var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth","Token");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
}
[Fact]
public async Task UnrecognizedTokenReceived()
{
var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("", response.ResponseText);
}
[Fact]
public async Task InvalidTokenReceived()
{
var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new InvalidTokenValidator());
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("Bearer error=\"invalid_token\"", response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Theory]
[InlineData(typeof(SecurityTokenInvalidAudienceException), "The audience is invalid")]
[InlineData(typeof(SecurityTokenInvalidIssuerException), "The issuer is invalid")]
[InlineData(typeof(SecurityTokenNoExpirationException), "The token has no expiration")]
[InlineData(typeof(SecurityTokenInvalidLifetimeException), "The token lifetime is invalid")]
[InlineData(typeof(SecurityTokenNotYetValidException), "The token is not valid yet")]
[InlineData(typeof(SecurityTokenExpiredException), "The token is expired")]
[InlineData(typeof(SecurityTokenInvalidSignatureException), "The signature is invalid")]
[InlineData(typeof(SecurityTokenSignatureKeyNotFoundException), "The signature key was not found")]
public async Task ExceptionReportedInHeaderForAuthenticationFailures(Type errorType, string message)
{
var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new InvalidTokenValidator(errorType));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal($"Bearer error=\"invalid_token\", error_description=\"{message}\"", response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Theory]
[InlineData(typeof(ArgumentException))]
public async Task ExceptionNotReportedInHeaderForOtherFailures(Type errorType)
{
var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new InvalidTokenValidator(errorType));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("Bearer error=\"invalid_token\"", response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Fact]
public async Task ExceptionsReportedInHeaderForMultipleAuthenticationFailures()
{
var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenInvalidAudienceException)));
options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenSignatureKeyNotFoundException)));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("Bearer error=\"invalid_token\", error_description=\"The audience is invalid; The signature key was not found\"",
response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Theory]
[InlineData("custom_error", "custom_description", "custom_uri")]
[InlineData("custom_error", "custom_description", null)]
[InlineData("custom_error", null, null)]
[InlineData(null, "custom_description", "custom_uri")]
[InlineData(null, "custom_description", null)]
[InlineData(null, null, "custom_uri")]
public async Task ExceptionsReportedInHeaderExposesUserDefinedError(string error, string description, string uri)
{
var options = new JwtBearerOptions
{
Events = new JwtBearerEvents
{
OnChallenge = context =>
{
context.Error = error;
context.ErrorDescription = description;
context.ErrorUri = uri;
return Task.FromResult(0);
}
}
};
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("", response.ResponseText);
var builder = new StringBuilder(options.Challenge);
if (!string.IsNullOrEmpty(error))
{
builder.Append(" error=\"");
builder.Append(error);
builder.Append("\"");
}
if (!string.IsNullOrEmpty(description))
{
if (!string.IsNullOrEmpty(error))
{
builder.Append(",");
}
builder.Append(" error_description=\"");
builder.Append(description);
builder.Append('\"');
}
if (!string.IsNullOrEmpty(uri))
{
if (!string.IsNullOrEmpty(error) ||
!string.IsNullOrEmpty(description))
{
builder.Append(",");
}
builder.Append(" error_uri=\"");
builder.Append(uri);
builder.Append('\"');
}
Assert.Equal(builder.ToString(), response.Response.Headers.WwwAuthenticate.First().ToString());
}
[Fact]
public async Task ExceptionNotReportedInHeaderWhenIncludeErrorDetailsIsFalse()
{
var server = CreateServer(new JwtBearerOptions
{
IncludeErrorDetails = false
});
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("Bearer", response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Fact]
public async Task ExceptionNotReportedInHeaderWhenTokenWasMissing()
{
var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/oauth");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
Assert.Equal("Bearer", response.Response.Headers.WwwAuthenticate.First().ToString());
Assert.Equal("", response.ResponseText);
}
[Fact]
public async Task CustomTokenValidated()
{
var options = new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
// Retrieve the NameIdentifier claim from the identity
// returned by the custom security token validator.
var identity = (ClaimsIdentity)context.Ticket.Principal.Identity;
var identifier = identity.FindFirst(ClaimTypes.NameIdentifier);
Assert.Equal("Bob le Tout Puissant", identifier.Value);
// Remove the existing NameIdentifier claim and replace it
// with a new one containing a different value.
identity.RemoveClaim(identifier);
// Make sure to use a different name identifier
// than the one defined by BlobTokenValidator.
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Bob le Magnifique"));
return Task.FromResult<object>(null);
}
}
};
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal("Bob le Magnifique", response.ResponseText);
}
[Fact]
public async Task RetrievingTokenFromAlternateLocation()
{
var options = new JwtBearerOptions()
{
Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
context.Token = "CustomToken";
return Task.FromResult<object>(null);
}
}
};
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT", token =>
{
Assert.Equal("CustomToken", token);
}));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal("Bob le Tout Puissant", response.ResponseText);
}
[Fact]
public async Task BearerTurns401To403IfAuthenticated()
{
var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token");
Assert.Equal(HttpStatusCode.Forbidden, response.Response.StatusCode);
}
[Fact]
public async Task BearerDoesNothingTo401IfNotAuthenticated()
{
var server = CreateServer(new JwtBearerOptions());
var response = await SendAsync(server, "http://example.com/unauthorized");
Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
}
[Fact]
public async Task EventOnMessageReceivedSkipped_NoMoreEventsExecuted()
{
var server = CreateServer(new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
context.SkipToNextMiddleware();
return Task.FromResult(0);
},
OnTokenValidated = context =>
{
throw new NotImplementedException();
},
OnAuthenticationFailed = context =>
{
throw new NotImplementedException(context.Exception.ToString());
},
OnChallenge = context =>
{
throw new NotImplementedException();
},
}
});
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal(string.Empty, response.ResponseText);
}
[Fact]
public async Task EventOnTokenValidatedSkipped_NoMoreEventsExecuted()
{
var options = new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
context.SkipToNextMiddleware();
return Task.FromResult(0);
},
OnAuthenticationFailed = context =>
{
throw new NotImplementedException(context.Exception.ToString());
},
OnChallenge = context =>
{
throw new NotImplementedException();
},
}
};
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal(string.Empty, response.ResponseText);
}
[Fact]
public async Task EventOnAuthenticationFailedSkipped_NoMoreEventsExecuted()
{
var options = new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnTokenValidated = context =>
{
throw new Exception("Test Exception");
},
OnAuthenticationFailed = context =>
{
context.SkipToNextMiddleware();
return Task.FromResult(0);
},
OnChallenge = context =>
{
throw new NotImplementedException();
},
}
};
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
var server = CreateServer(options);
var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Equal(string.Empty, response.ResponseText);
}
[Fact]
public async Task EventOnChallengeSkipped_ResponseNotModified()
{
var server = CreateServer(new JwtBearerOptions
{
Events = new JwtBearerEvents()
{
OnChallenge = context =>
{
context.SkipToNextMiddleware();
return Task.FromResult(0);
},
}
});
var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token");
Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
Assert.Empty(response.Response.Headers.WwwAuthenticate);
Assert.Equal(string.Empty, response.ResponseText);
}
class InvalidTokenValidator : ISecurityTokenValidator
{
public InvalidTokenValidator()
{
ExceptionType = typeof(SecurityTokenException);
}
public InvalidTokenValidator(Type exceptionType)
{
ExceptionType = exceptionType;
}
public Type ExceptionType { get; set; }
public bool CanValidateToken => true;
public int MaximumTokenSizeInBytes
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool CanReadToken(string securityToken) => true;
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
var constructor = ExceptionType.GetTypeInfo().GetConstructor(new[] { typeof(string) });
var exception = (Exception)constructor.Invoke(new[] { ExceptionType.Name });
throw exception;
}
}
class BlobTokenValidator : ISecurityTokenValidator
{
private Action<string> _tokenValidator;
public BlobTokenValidator(string authenticationScheme)
{
AuthenticationScheme = authenticationScheme;
}
public BlobTokenValidator(string authenticationScheme, Action<string> tokenValidator)
{
AuthenticationScheme = authenticationScheme;
_tokenValidator = tokenValidator;
}
public string AuthenticationScheme { get; }
public bool CanValidateToken => true;
public int MaximumTokenSizeInBytes
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool CanReadToken(string securityToken) => true;
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
validatedToken = null;
if (_tokenValidator != null)
{
_tokenValidator(securityToken);
}
var claims = new[]
{
// Make sure to use a different name identifier
// than the one defined by CustomTokenValidated.
new Claim(ClaimTypes.NameIdentifier, "Bob le Tout Puissant"),
new Claim(ClaimTypes.Email, "bob@contoso.com"),
new Claim(ClaimsIdentity.DefaultNameClaimType, "bob"),
};
return new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationScheme));
}
}
private static TestServer CreateServer(JwtBearerOptions options, Func<HttpContext, bool> handler = null)
{
var builder = new WebHostBuilder()
.Configure(app =>
{
if (options != null)
{
app.UseJwtBearerAuthentication(options);
}
app.Use(async (context, next) =>
{
if (context.Request.Path == new PathString("/checkforerrors"))
{
var authContext = new AuthenticateContext(Http.Authentication.AuthenticationManager.AutomaticScheme);
await context.Authentication.AuthenticateAsync(authContext);
if (authContext.Error != null)
{
throw new Exception("Failed to authenticate", authContext.Error);
}
return;
}
else if (context.Request.Path == new PathString("/oauth"))
{
if (context.User == null ||
context.User.Identity == null ||
!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
return;
}
var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier);
if (identifier == null)
{
context.Response.StatusCode = 500;
return;
}
await context.Response.WriteAsync(identifier.Value);
}
else if (context.Request.Path == new PathString("/unauthorized"))
{
// Simulate Authorization failure
var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
}
else if (context.Request.Path == new PathString("/signIn"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal()));
}
else if (context.Request.Path == new PathString("/signOut"))
{
await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme));
}
else
{
await next();
}
});
})
.ConfigureServices(services => services.AddAuthentication());
return new TestServer(builder);
}
// TODO: see if we can share the TestExtensions SendAsync method (only diff is auth header)
private static async Task<Transaction> SendAsync(TestServer server, string uri, string authorizationHeader = null)
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
if (!string.IsNullOrEmpty(authorizationHeader))
{
request.Headers.Add("Authorization", authorizationHeader);
}
var transaction = new Transaction
{
Request = request,
Response = await server.CreateClient().SendAsync(request),
};
transaction.ResponseText = await transaction.Response.Content.ReadAsStringAsync();
if (transaction.Response.Content != null &&
transaction.Response.Content.Headers.ContentType != null &&
transaction.Response.Content.Headers.ContentType.MediaType == "text/xml")
{
transaction.ResponseElement = XElement.Parse(transaction.ResponseText);
}
return transaction;
}
}
}