This repository has been archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
FormsAuthenticationFixture.cs
815 lines (643 loc) · 32.7 KB
/
FormsAuthenticationFixture.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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
namespace Nancy.Authentication.Forms.Tests
{
using System;
using System.Linq;
using System.Threading;
using Bootstrapper;
using Cryptography;
using FakeItEasy;
using Fakes;
using Helpers;
using Nancy.Tests;
using Nancy.Tests.Fakes;
using Xunit;
public class FormsAuthenticationFixture
{
private FormsAuthenticationConfiguration config;
private FormsAuthenticationConfiguration secureConfig;
private FormsAuthenticationConfiguration domainPathConfig;
private NancyContext context;
private Guid userGuid;
private string validCookieValue =
HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9");
private string cookieWithNoHmac =
HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9");
private string cookieWithEmptyHmac =
HttpUtility.UrlEncode("k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9");
private string cookieWithInvalidHmac =
HttpUtility.UrlEncode("C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9");
private string cookieWithBrokenEncryptedData =
HttpUtility.UrlEncode("C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9");
private CryptographyConfiguration cryptographyConfiguration;
private string domain = ".nancyfx.org";
private string path = "/";
public FormsAuthenticationFixture()
{
this.cryptographyConfiguration = new CryptographyConfiguration(
new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)),
new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)));
this.config = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false
};
this.secureConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = true
};
this.domainPathConfig = new FormsAuthenticationConfiguration()
{
CryptographyConfiguration = this.cryptographyConfiguration,
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
RequiresSSL = false,
Domain = domain,
Path = path
};
this.context = new NancyContext
{
Request = new Request(
"GET",
new Url { Scheme = "http", BasePath = "/testing", HostName = "test.com", Path = "test" })
};
this.userGuid = new Guid("3D97EB33-824A-4173-A2C1-633AC16C1010");
}
[Fact]
public void Should_throw_with_null_application_pipelines_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_invalid_config_passed_to_enable()
{
var fakeConfig = A.Fake<FormsAuthenticationConfiguration>();
A.CallTo(() => fakeConfig.IsValid).Returns(false);
var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig));
result.ShouldBeOfType(typeof(ArgumentException));
}
[Fact]
public void Should_add_a_pre_and_post_hook_when_enabled()
{
var pipelines = A.Fake<IPipelines>();
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true()
{
var pipelines = A.Fake<IPipelines>();
this.config.DisableRedirect = true;
FormsAuthentication.Enable(pipelines, this.config);
A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))
.MustNotHaveHappened();
}
[Fact]
public void Should_return_redirect_response_when_user_logs_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
#region Throw helpful exception when the configuration is not enabled
[Fact]
public void Should_throw_helpful_exception_message_when_user_logs_in_without_redirect_and_forms_authentication_not_enabled()
{
// Given
const string expectedMessage = "The internal FormsAuthenticationConfiguration has not been set. Ensure that FormsAuthentication has been enabled in the bootstrapper";
FormsAuthentication.Disable();
// When
var result = Record.Exception(() => FormsAuthentication.UserLoggedInResponse(userGuid));
// Then
result.ShouldBeOfType(typeof(InvalidOperationException));
result.Message.ShouldBeSameAs(expectedMessage);
}
[Fact]
public void Should_throw_helpful_exception_message_when_user_logs_in_with_redirect_and_forms_authentication_not_enabled()
{
// Given
const string expectedMessage = "The internal FormsAuthenticationConfiguration has not been set. Ensure that FormsAuthentication has been enabled in the bootstrapper";
FormsAuthentication.Disable();
// When
var result = Record.Exception(() => FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid));
// Then
result.ShouldBeOfType(typeof(InvalidOperationException));
result.Message.ShouldBeSameAs(expectedMessage);
}
[Fact]
public void Should_throw_helpful_exception_message_when_user_logs_out_with_redirect_and_forms_authentication_not_enabled()
{
// Given
const string expectedMessage = "The internal FormsAuthenticationConfiguration has not been set. Ensure that FormsAuthentication has been enabled in the bootstrapper";
FormsAuthentication.Disable();
// When
var result = Record.Exception(() => FormsAuthentication.LogOutAndRedirectResponse(context, "/"));
// Then
result.ShouldBeOfType(typeof(InvalidOperationException));
result.Message.ShouldBeSameAs(expectedMessage);
}
[Fact]
public void Should_throw_helpful_exception_message_when_user_logs_out_without_redirect_and_forms_authentication_not_enabled()
{
// Given
const string expectedMessage = "The internal FormsAuthenticationConfiguration has not been set. Ensure that FormsAuthentication has been enabled in the bootstrapper";
FormsAuthentication.Disable();
// When
var result = Record.Exception(() => FormsAuthentication.LogOutResponse());
// Then
result.ShouldBeOfType(typeof(InvalidOperationException));
result.Message.ShouldBeSameAs(expectedMessage);
}
#endregion
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.HttpOnly.ShouldBeTrue();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()
.Expires.ShouldNotBeNull();
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_with_redirect()
{
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_encrypt_cookie_when_logging_in_without_redirect()
{
// Given
var mockEncrypter = A.Fake<IEncryptionProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect()
{
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect()
{
// Given
var fakeEncrypter = A.Fake<IEncryptionProvider>();
var fakeCryptoText = "FakeText";
A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))
.Returns(fakeCryptoText);
var mockHmac = A.Fake<IHmacProvider>();
this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));
// Then
A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_return_redirect_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
}
[Fact]
public void Should_return_ok_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.OK);
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Value.ShouldBeEmpty();
cookie.Expires.ShouldNotBeNull();
(cookie.Expires < DateTime.Now).ShouldBeTrue();
}
[Fact]
public void Should_get_username_from_mapping_service_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var mockMapper = A.Fake<IUserMapper>();
this.config.UserMapper = mockMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_set_user_in_context_with_valid_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity {UserName = "Bob"};
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeSameAs(fakeUser);
}
[Fact]
public void Should_not_set_user_in_context_with_empty_cookie()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity {UserName = "Bob"};
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_invalid_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity { UserName = "Bob" };
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_empty_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity { UserName = "Bob" };
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_user_in_context_with_no_hmac()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity { UserName = "Bob" };
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_not_set_username_in_context_with_broken_encryption_data()
{
var fakePipelines = new Pipelines();
var fakeMapper = A.Fake<IUserMapper>();
var fakeUser = new FakeUserIdentity { UserName = "Bob" };
A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);
this.config.UserMapper = fakeMapper;
FormsAuthentication.Enable(fakePipelines, this.config);
this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData);
var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());
context.CurrentUser.ShouldBeNull();
}
[Fact]
public void Should_retain_querystring_when_redirecting_to_login_page()
{
// Given
var fakePipelines = new Pipelines();
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = "next";
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?next=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = null;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty()
{
// Given
var fakePipelines = new Pipelines();
this.config.RedirectQuerystringKey = string.Empty;
FormsAuthentication.Enable(fakePipelines, this.config);
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "?foo=bar"),
Response = HttpStatusCode.Unauthorized
};
// When
fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());
// Then
queryContext.Response.Headers["Location"].ShouldEqual("/login?returnUrl=/secure%3ffoo%3dbar");
}
[Fact]
public void Should_retain_querystring_when_redirecting_after_successfull_login()
{
// Given
var queryContext = new NancyContext()
{
Request = new FakeRequest("GET", "/secure", "returnUrl=/secure%3Ffoo%3Dbar")
};
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
// When
var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1));
// Then
result.Headers["Location"].ShouldEqual("/secure?foo=bar");
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.UserLoggedInResponse(userGuid);
// Then
result.Cookies
.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)
.First()
.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
var result = FormsAuthentication.LogOutAndRedirectResponse(context, "/");
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect()
{
// Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);
// When
var result = FormsAuthentication.LogOutResponse();
// Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Secure.ShouldBeTrue();
}
[Fact]
public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing");
}
[Fact]
public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "http://moo.com/";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:"/moo");
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/moo");
}
[Fact]
public void Should_redirect_to_given_url_if_local()
{
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);
context.Request.Query[config.RedirectQuerystringKey] = "~/login";
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
result.ShouldBeOfType(typeof(Response));
result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);
result.Headers["Location"].ShouldEqual("/testing/login");
}
[Fact]
public void Should_set_Domain_when_config_provides_domain_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Domain.ShouldEqual(domain);
}
[Fact]
public void Should_set_Path_when_config_provides_path_value()
{
//Given
FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);
//When
var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);
//Then
var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();
cookie.Path.ShouldEqual(path);
}
[Fact]
public void Should_throw_with_null_module_passed_to_enable()
{
var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_with_null_config_passed_to_enable_with_module()
{
var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null));
result.ShouldBeOfType(typeof(ArgumentNullException));
}
class FakeModule : NancyModule
{
public FakeModule()
{
this.After = new AfterPipeline();
this.Before = new BeforePipeline();
this.OnError = new ErrorPipeline();
}
}
}
}