Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CookieTests.cs « test « Authentication « Security « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d4169b2e6c1c83394403eefd66883ca22cea955d (plain)
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Xml.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication.Cookies;

public class CookieTests : SharedAuthenticationTests<CookieAuthenticationOptions>
{
    private readonly TestClock _clock = new TestClock();

    protected override string DefaultScheme => CookieAuthenticationDefaults.AuthenticationScheme;
    protected override Type HandlerType => typeof(CookieAuthenticationHandler);

    protected override void RegisterAuth(AuthenticationBuilder services, Action<CookieAuthenticationOptions> configure)
    {
        services.AddCookie(configure);
    }

    [Fact]
    public async Task NormalRequestPassesThrough()
    {
        using var host = await CreateHost(s => { });
        using var server = host.GetTestServer();
        var response = await server.CreateClient().GetAsync("http://example.com/normal");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task AjaxLoginRedirectToReturnUrlTurnsInto200WithLocationHeader()
    {
        using var host = await CreateHost(o => o.LoginPath = "/login");
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/challenge?X-Requested-With=XMLHttpRequest");
        Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode);
        var responded = transaction.Response.Headers.GetValues("Location");
        Assert.Single(responded);
        Assert.StartsWith("http://example.com/login", responded.Single());
    }

    [Fact]
    public async Task AjaxForbidTurnsInto403WithLocationHeader()
    {
        using var host = await CreateHost(o => o.AccessDeniedPath = "/denied");
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/forbid?X-Requested-With=XMLHttpRequest");
        Assert.Equal(HttpStatusCode.Forbidden, transaction.Response.StatusCode);
        var responded = transaction.Response.Headers.GetValues("Location");
        Assert.Single(responded);
        Assert.StartsWith("http://example.com/denied", responded.Single());
    }

    [Fact]
    public async Task AjaxLogoutRedirectToReturnUrlTurnsInto200WithLocationHeader()
    {
        using var host = await CreateHost(o => o.LogoutPath = "/signout");
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/signout?X-Requested-With=XMLHttpRequest&ReturnUrl=/");
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
        var responded = transaction.Response.Headers.GetValues("Location");
        Assert.Single(responded);
        Assert.StartsWith("/", responded.Single());
    }

    [Fact]
    public async Task AjaxChallengeRedirectTurnsInto200WithLocationHeader()
    {
        using var host = await CreateHost(s => { });
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/challenge?X-Requested-With=XMLHttpRequest&ReturnUrl=/");
        Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode);
        var responded = transaction.Response.Headers.GetValues("Location");
        Assert.Single(responded);
        Assert.StartsWith("http://example.com/Account/Login", responded.Single());
    }

    [Fact]
    public async Task ProtectedCustomRequestShouldRedirectToCustomRedirectUri()
    {
        using var host = await CreateHost(s => { });
        using var server = host.GetTestServer();

        var transaction = await SendAsync(server, "http://example.com/protected/CustomRedirect");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        var location = transaction.Response.Headers.Location;
        Assert.Equal("http://example.com/Account/Login?ReturnUrl=%2FCustomRedirect", location.ToString());
    }

    private static Task SignInAsAlice(HttpContext context)
    {
        var user = new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"));
        user.AddClaim(new Claim("marker", "true"));
        return context.SignInAsync("Cookies",
            new ClaimsPrincipal(user),
            new AuthenticationProperties());
    }

    private static Task SignInAsWrong(HttpContext context)
    {
        return context.SignInAsync("Oops",
            new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
            new AuthenticationProperties());
    }

    private Task SignOutAsWrong(HttpContext context)
    {
        return context.SignOutAsync("Oops");
    }

    [Fact]
    public async Task SignInCausesDefaultCookieToBeCreated()
    {
        using var host = await CreateHostWithServices(s => s.AddAuthentication().AddCookie(o =>
        {
            o.LoginPath = new PathString("/login");
            o.Cookie.Name = "TestCookie";
        }), SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath");

        var setCookie = transaction.SetCookie;
        Assert.StartsWith("TestCookie=", setCookie);
        Assert.Contains("; path=/", setCookie);
        Assert.Contains("; httponly", setCookie);
        Assert.Contains("; samesite=", setCookie);
        Assert.DoesNotContain("; expires=", setCookie);
        Assert.DoesNotContain("; domain=", setCookie);
        Assert.DoesNotContain("; secure", setCookie);
        Assert.True(transaction.Response.Headers.CacheControl.NoCache);
        Assert.True(transaction.Response.Headers.CacheControl.NoStore);
        Assert.Equal("no-cache", transaction.Response.Headers.Pragma.ToString());
    }

    private class TestTicketStore : ITicketStore
    {
        private const string KeyPrefix = "AuthSessionStore-";
        public readonly Dictionary<string, AuthenticationTicket> Store = new Dictionary<string, AuthenticationTicket>();

        public async Task<string> StoreAsync(AuthenticationTicket ticket)
        {
            var guid = Guid.NewGuid();
            var key = KeyPrefix + guid.ToString();
            await RenewAsync(key, ticket);
            return key;
        }

        public Task RenewAsync(string key, AuthenticationTicket ticket)
        {
            Store[key] = ticket;

            return Task.FromResult(0);
        }

        public Task<AuthenticationTicket> RetrieveAsync(string key)
        {
            AuthenticationTicket ticket;
            Store.TryGetValue(key, out ticket);
            return Task.FromResult(ticket);
        }

        public Task RemoveAsync(string key)
        {
            Store.Remove(key);
            return Task.FromResult(0);
        }
    }

    [Fact]
    public async Task SignInWithTicketStoreWorks()
    {
        var sessionStore = new TestTicketStore();
        using var host = await CreateHostWithServices(s =>
        {
            s.AddSingleton<ISystemClock>(_clock);
            s.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
            {
                o.SessionStore = sessionStore;
            });
        }, SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        // Make sure we have one key as the session id
        var key1 = Assert.Single(sessionStore.Store.Keys);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        // Make sure the session is expired
        _clock.Add(TimeSpan.FromDays(60));

        // Verify that a new session is generated with a new key
        var transaction3 = await SendAsync(server, "http://example.com/signinalice", transaction1.CookieNameValue);

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);

        var key2 = Assert.Single(sessionStore.Store.Keys);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));
        Assert.NotEqual(key1, key2);
    }

    [Fact]
    public async Task SessionStoreRemovesExpired()
    {
        var sessionStore = new TestTicketStore();
        using var host = await CreateHostWithServices(s =>
        {
            s.AddSingleton<ISystemClock>(_clock);
            s.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
            {
                o.SessionStore = sessionStore;
            });
        }, SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        // Make sure we have one key as the session id
        var key1 = Assert.Single(sessionStore.Store.Keys);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        // Make sure the session is expired
        _clock.Add(TimeSpan.FromDays(60));

        // Verify that a new session is generated with a new key
        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        Assert.Empty(sessionStore.Store.Keys);
        Assert.Null(FindClaimValue(transaction3, ClaimTypes.Name));
    }

    [Fact]
    public async Task CustomAuthSchemeEncodesCookieName()
    {
        var schemeName = "With spaces and 界";
        using var host = await CreateHostWithServices(s => s.AddAuthentication(schemeName).AddCookie(schemeName, o =>
        {
            o.LoginPath = new PathString("/login");
        }), context =>
        {
            var user = new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"));
            user.AddClaim(new Claim("marker", "true"));
            return context.SignInAsync(schemeName,
                new ClaimsPrincipal(user),
                new AuthenticationProperties());
        });

        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath");

        var setCookie = transaction.SetCookie;
        Assert.StartsWith(".AspNetCore.With%20spaces%20and%20%E7%95%8C=", setCookie);
        Assert.Contains("; path=/", setCookie);
        Assert.Contains("; httponly", setCookie);
        Assert.Contains("; samesite=", setCookie);
        Assert.DoesNotContain("; expires=", setCookie);
        Assert.DoesNotContain("; domain=", setCookie);
        Assert.DoesNotContain("; secure", setCookie);
        Assert.True(transaction.Response.Headers.CacheControl.NoCache);
        Assert.True(transaction.Response.Headers.CacheControl.NoStore);
        Assert.Equal("no-cache", transaction.Response.Headers.Pragma.ToString());
    }

    [Fact]
    public void SettingCookieExpirationOptionThrows()
    {
        var services = new ServiceCollection();
        services.AddAuthentication().AddCookie(o =>
        {
            o.Cookie.Expiration = TimeSpan.FromDays(10);
        });
        var options = services.BuildServiceProvider().GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>();
        Assert.Throws<OptionsValidationException>(() => options.Get(CookieAuthenticationDefaults.AuthenticationScheme));
    }

    [Fact]
    public async Task SignInWrongAuthTypeThrows()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = new PathString("/login");
            o.Cookie.Name = "TestCookie";
        }, SignInAsWrong);
        using var server = host.GetTestServer();

        await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath"));
    }

    [Fact]
    public async Task SignOutWrongAuthTypeThrows()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = new PathString("/login");
            o.Cookie.Name = "TestCookie";
        }, SignOutAsWrong);

        using var server = host.GetTestServer();
        await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendAsync(server, "http://example.com/testpath"));
    }

    [Theory]
    [InlineData(CookieSecurePolicy.Always, "http://example.com/testpath", true)]
    [InlineData(CookieSecurePolicy.Always, "https://example.com/testpath", true)]
    [InlineData(CookieSecurePolicy.None, "http://example.com/testpath", false)]
    [InlineData(CookieSecurePolicy.None, "https://example.com/testpath", false)]
    [InlineData(CookieSecurePolicy.SameAsRequest, "http://example.com/testpath", false)]
    [InlineData(CookieSecurePolicy.SameAsRequest, "https://example.com/testpath", true)]
    public async Task SecureSignInCausesSecureOnlyCookieByDefault(
        CookieSecurePolicy cookieSecurePolicy,
        string requestUri,
        bool shouldBeSecureOnly)
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = new PathString("/login");
            o.Cookie.Name = "TestCookie";
            o.Cookie.SecurePolicy = cookieSecurePolicy;
        }, SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, requestUri);
        var setCookie = transaction.SetCookie;

        if (shouldBeSecureOnly)
        {
            Assert.Contains("; secure", setCookie);
        }
        else
        {
            Assert.DoesNotContain("; secure", setCookie);
        }
    }

    [Fact]
    public async Task CookieOptionsAlterSetCookieHeader()
    {
        using var host = await CreateHost(o =>
        {
            o.Cookie.Name = "TestCookie";
            o.Cookie.Path = "/foo";
            o.Cookie.Domain = "another.com";
            o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            o.Cookie.SameSite = SameSiteMode.None;
            o.Cookie.HttpOnly = true;
            o.Cookie.Extensions.Add("extension0");
            o.Cookie.Extensions.Add("extension1=value1");
        }, SignInAsAlice, baseAddress: new Uri("http://example.com/base"));

        using var server1 = host.GetTestServer();
        var transaction1 = await SendAsync(server1, "http://example.com/base/testpath");

        var setCookie1 = transaction1.SetCookie;

        Assert.Contains("TestCookie=", setCookie1);
        Assert.Contains(" path=/foo", setCookie1);
        Assert.Contains(" domain=another.com", setCookie1);
        Assert.Contains(" secure", setCookie1);
        Assert.Contains(" samesite=none", setCookie1);
        Assert.Contains(" httponly", setCookie1);
        Assert.Contains(" extension0", setCookie1);
        Assert.Contains(" extension1=value1", setCookie1);

        using var host2 = await CreateHost(o =>
        {
            o.Cookie.Name = "SecondCookie";
            o.Cookie.SecurePolicy = CookieSecurePolicy.None;
            o.Cookie.SameSite = SameSiteMode.Strict;
            o.Cookie.HttpOnly = false;
        }, SignInAsAlice, baseAddress: new Uri("http://example.com/base"));

        using var server2 = host2.GetTestServer();
        var transaction2 = await SendAsync(server2, "http://example.com/base/testpath");

        var setCookie2 = transaction2.SetCookie;

        Assert.Contains("SecondCookie=", setCookie2);
        Assert.Contains(" path=/base", setCookie2);
        Assert.Contains(" samesite=strict", setCookie2);
        Assert.DoesNotContain(" domain=", setCookie2);
        Assert.DoesNotContain(" secure", setCookie2);
        Assert.DoesNotContain(" httponly", setCookie2);
        Assert.DoesNotContain(" extension", setCookie2);
    }

    [Fact]
    public async Task CookieContainsIdentity()
    {
        using var host = await CreateHost(o => { }, SignInAsAlice);
        using var server = host.GetTestServer();

        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieAppliesClaimsTransform()
    {
        using var host = await CreateHost(o => { },
        SignInAsAlice,
        baseAddress: null,
        claimsTransform: true);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        Assert.Equal("yup", FindClaimValue(transaction2, "xform"));
        Assert.Null(FindClaimValue(transaction2, "sync"));
    }

    [Fact]
    public async Task CookieStopsWorkingAfterExpiration()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
        }, SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        _clock.Add(TimeSpan.FromMinutes(7));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        _clock.Add(TimeSpan.FromMinutes(7));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
        Assert.Null(transaction4.SetCookie);
        Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieExpirationCanBeOverridenInSignin()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                new AuthenticationProperties() { ExpiresUtc = _clock.UtcNow.Add(TimeSpan.FromMinutes(5)) }));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        _clock.Add(TimeSpan.FromMinutes(3));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        _clock.Add(TimeSpan.FromMinutes(3));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
        Assert.Null(transaction4.SetCookie);
        Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
    }

    [Fact]
    public async Task ExpiredCookieWithValidatorStillExpired()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        _clock.Add(TimeSpan.FromMinutes(11));

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction2.SetCookie);
        Assert.Null(FindClaimValue(transaction2, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieCanBeRejectedAndSignedOutByValidator()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.RejectPrincipal();
                    ctx.HttpContext.SignOutAsync("Cookies");
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Contains(".AspNetCore.Cookies=; expires=", transaction2.SetCookie);
        Assert.Null(FindClaimValue(transaction2, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieNotRenewedAfterSignOut()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        // renews on every request
        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        var transaction3 = await server.SendAsync("http://example.com/normal", transaction1.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie[0]);

        // signout wins over renew
        var transaction4 = await server.SendAsync("http://example.com/signout", transaction3.SetCookie[0]);
        Assert.Single(transaction4.SetCookie);
        Assert.Contains(".AspNetCore.Cookies=; expires=", transaction4.SetCookie[0]);
    }

    [Fact]
    public async Task CookieCanBeRenewedByValidator()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(6));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction4.SetCookie);
        Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieCanBeReplacedByValidator()
    {
        using var host = await CreateHost(o =>
        {
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    ctx.ReplacePrincipal(new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice2", "Cookies2"))));
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice2", FindClaimValue(transaction2, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieCanBeUpdatedByValidatorDuringRefresh()
    {
        var replace = false;
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    if (replace)
                    {
                        ctx.ShouldRenew = true;
                        ctx.ReplacePrincipal(new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice2", "Cookies2"))));
                        ctx.Properties.Items["updated"] = "yes";
                    }
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
        Assert.Null(FindPropertiesValue(transaction3, "updated"));

        replace = true;

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("Alice2", FindClaimValue(transaction4, ClaimTypes.Name));
        Assert.Equal("yes", FindPropertiesValue(transaction4, "updated"));

        replace = false;

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Equal("Alice2", FindClaimValue(transaction5, ClaimTypes.Name));
        Assert.Equal("yes", FindPropertiesValue(transaction4, "updated"));
    }

    [Fact]
    public async Task CookieCanBeRenewedByValidatorWithSlidingExpiry()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(6));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(11));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieCanBeRenewedByValidatorWithModifiedProperties()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    var id = ctx.Principal.Identities.First();
                    var claim = id.FindFirst("counter");
                    if (claim == null)
                    {
                        id.AddClaim(new Claim("counter", "1"));
                    }
                    else
                    {
                        id.RemoveClaim(claim);
                        id.AddClaim(new Claim("counter", claim.Value + "1"));
                    }
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("1", FindClaimValue(transaction2, "counter"));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("11", FindClaimValue(transaction3, "counter"));

        _clock.Add(TimeSpan.FromMinutes(6));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("111", FindClaimValue(transaction4, "counter"));

        _clock.Add(TimeSpan.FromMinutes(11));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Null(FindClaimValue(transaction5, "counter"));
    }

    [Fact]
    public async Task CookieCanBeRenewedByValidatorWithModifiedLifetime()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    var id = ctx.Principal.Identities.First();
                    var claim = id.FindFirst("counter");
                    if (claim == null)
                    {
                        id.AddClaim(new Claim("counter", "1"));
                    }
                    else
                    {
                        id.RemoveClaim(claim);
                        id.AddClaim(new Claim("counter", claim.Value + "1"));
                    }
                    // Causes the expiry time to not be extended because the lifetime is
                    // calculated relative to the issue time.
                    ctx.Properties.IssuedUtc = _clock.UtcNow;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("1", FindClaimValue(transaction2, "counter"));

        _clock.Add(TimeSpan.FromMinutes(1));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("11", FindClaimValue(transaction3, "counter"));

        _clock.Add(TimeSpan.FromMinutes(1));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("111", FindClaimValue(transaction4, "counter"));

        _clock.Add(TimeSpan.FromMinutes(9));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Null(FindClaimValue(transaction5, "counter"));
    }

    [Fact]
    public async Task CookieValidatorOnlyCalledOnce()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(6));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction4.SetCookie);
        Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(5));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
    }

    [Theory]
    [InlineData(true)]
    [InlineData(false)]
    public async Task ShouldRenewUpdatesIssuedExpiredUtc(bool sliding)
    {
        DateTimeOffset? lastValidateIssuedDate = null;
        DateTimeOffset? lastExpiresDate = null;
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = sliding;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = ctx =>
                {
                    lastValidateIssuedDate = ctx.Properties.IssuedUtc;
                    lastExpiresDate = ctx.Properties.ExpiresUtc;
                    ctx.ShouldRenew = true;
                    return Task.FromResult(0);
                }
            };
        },
        context =>
            context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        Assert.NotNull(lastValidateIssuedDate);
        Assert.NotNull(lastExpiresDate);

        var firstIssueDate = lastValidateIssuedDate;
        var firstExpiresDate = lastExpiresDate;

        _clock.Add(TimeSpan.FromMinutes(1));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
        Assert.NotNull(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(2));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

        Assert.NotEqual(lastValidateIssuedDate, firstIssueDate);
        Assert.NotEqual(firstExpiresDate, lastExpiresDate);
    }

    [Fact]
    public async Task CookieExpirationCanBeOverridenInEvent()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = false;
            o.Events = new CookieAuthenticationEvents()
            {
                OnSigningIn = context =>
                {
                    context.Properties.ExpiresUtc = _clock.UtcNow.Add(TimeSpan.FromMinutes(5));
                    return Task.FromResult(0);
                }
            };
        },
        SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(3));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(3));

        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction4.SetCookie);
        Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieIsRenewedWithSlidingExpiration()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = true;
        },
        SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        // transaction4 should arrive with a new SetCookie value
        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieIsRenewedWithSlidingExpirationWithoutTransformations()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = true;
            o.Events.OnValidatePrincipal = c =>
            {
                // https://github.com/aspnet/Security/issues/1607
                // On sliding refresh the transformed principal should not be serialized into the cookie, only the original principal.
                Assert.Single(c.Principal.Identities);
                Assert.True(c.Principal.Identities.First().HasClaim("marker", "true"));
                return Task.CompletedTask;
            };
        },
        SignInAsAlice,
        claimsTransform: true);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        // transaction4 should arrive with a new SetCookie value
        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
        Assert.NotNull(transaction4.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
        Assert.Null(transaction5.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieIsRenewedWithSlidingExpirationEvent()
    {
        using var host = await CreateHost(o =>
        {
            o.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            o.SlidingExpiration = true;
            o.Events = new CookieAuthenticationEvents()
            {
                OnCheckSlidingExpiration = context =>
                {
                    var expectRenew = string.Equals("1", context.Request.Query["expectrenew"]);
                    var renew = string.Equals("1", context.Request.Query["renew"]);
                    Assert.Equal(expectRenew, context.ShouldRenew);
                    context.ShouldRenew = renew;
                    return Task.CompletedTask;
                }
            };
        },
        SignInAsAlice);

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/me/Cookies?expectrenew=0&renew=0", transaction1.CookieNameValue);
        Assert.Null(transaction2.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        var transaction3 = await SendAsync(server, "http://example.com/me/Cookies?expectrenew=0&renew=0", transaction1.CookieNameValue);
        Assert.Null(transaction3.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

        _clock.Add(TimeSpan.FromMinutes(4));

        // A renewal is now expected, but we've suppressed it
        var transaction4 = await SendAsync(server, "http://example.com/me/Cookies?expectrenew=1&renew=0", transaction1.CookieNameValue);
        Assert.Null(transaction4.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

        // Allow the default renewal to happen
        var transaction5 = await SendAsync(server, "http://example.com/me/Cookies?expectrenew=1&renew=1", transaction1.CookieNameValue);
        Assert.NotNull(transaction5.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name));

        // Force a renewal on an un-expired new cookie
        var transaction6 = await SendAsync(server, "http://example.com/me/Cookies?expectrenew=0&renew=1", transaction5.CookieNameValue);
        Assert.NotNull(transaction5.SetCookie);
        Assert.Equal("Alice", FindClaimValue(transaction6, ClaimTypes.Name));
    }

    [Fact]
    public async Task CookieUsesPathBaseByDefault()
    {
        using var host = await CreateHost(o => { },
        context =>
        {
            Assert.Equal(new PathString("/base"), context.Request.PathBase);
            return context.SignInAsync("Cookies",
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))));
        },
        new Uri("http://example.com/base"));

        using var server = host.GetTestServer();
        var transaction1 = await SendAsync(server, "http://example.com/base/testpath");
        Assert.Contains("path=/base", transaction1.SetCookie);
    }

    [Fact]
    public async Task CookieChallengeRedirectsToLoginWithoutCookie()
    {
        using var host = await CreateHost(o => { }, SignInAsAlice);

        var url = "http://example.com/challenge";
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, url);

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        var location = transaction.Response.Headers.Location;
        Assert.Equal("/Account/Login", location.LocalPath);
    }

    [Fact]
    public async Task CookieForbidRedirectsWithoutCookie()
    {
        using var host = await CreateHost(o => { }, SignInAsAlice);

        var url = "http://example.com/forbid";
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, url);

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        var location = transaction.Response.Headers.Location;
        Assert.Equal("/Account/AccessDenied", location.LocalPath);
    }

    [Fact]
    public async Task CookieChallengeRedirectsWithLoginPath()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = new PathString("/page");
        });
        using var server = host.GetTestServer();

        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/challenge", transaction1.CookieNameValue);

        Assert.Equal(HttpStatusCode.Redirect, transaction2.Response.StatusCode);
    }

    [Fact]
    public async Task CookieChallengeWithUnauthorizedRedirectsToLoginIfNotAuthenticated()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = new PathString("/page");
        });
        using var server = host.GetTestServer();

        var transaction1 = await SendAsync(server, "http://example.com/testpath");

        var transaction2 = await SendAsync(server, "http://example.com/unauthorized", transaction1.CookieNameValue);

        Assert.Equal(HttpStatusCode.Redirect, transaction2.Response.StatusCode);
    }

    [Theory]
    [InlineData(true)]
    [InlineData(false)]
    public async Task MapWillAffectChallengeOnlyWithUseAuth(bool useAuth)
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        if (useAuth)
                        {
                            app.UseAuthentication();
                        }
                        app.Map("/login", signoutApp => signoutApp.Run(context => context.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" })));
                    })
                    .ConfigureServices(s => s.AddAuthentication().AddCookie(o => o.LoginPath = new PathString("/page"))))
            .Build();
        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com/login");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);

        var location = transaction.Response.Headers.Location;
        if (useAuth)
        {
            Assert.Equal("/page", location.LocalPath);
        }
        else
        {
            Assert.Equal("/login/page", location.LocalPath);
        }
        Assert.Equal("?ReturnUrl=%2F", location.Query);
    }

    [ConditionalFact(Skip = "Revisit, exception no longer thrown")]
    public async Task ChallengeDoesNotSet401OnUnauthorized()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                .Configure(app =>
                {
                    app.UseAuthentication();
                    app.Run(async context =>
                    {
                        await Assert.ThrowsAsync<InvalidOperationException>(() => context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme));
                    });
                })
                .ConfigureServices(services => services.AddAuthentication().AddCookie()))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com");
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
    }

    [Fact]
    public async Task CanConfigureDefaultCookieInstance()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Run(context => context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity("whatever"))));
                    })
                    .ConfigureServices(services =>
                    {
                        services.AddAuthentication().AddCookie();
                        services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme,
                            o => o.Cookie.Name = "One");
                    }))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com");

        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
        Assert.StartsWith("One=", transaction.SetCookie[0]);
    }

    [Fact]
    public async Task CanConfigureNamedCookieInstance()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Run(context => context.SignInAsync("Cookie1", new ClaimsPrincipal(new ClaimsIdentity("whatever"))));
                    })
                    .ConfigureServices(services =>
                    {
                        services.AddAuthentication().AddCookie("Cookie1");
                        services.Configure<CookieAuthenticationOptions>("Cookie1",
                            o => o.Cookie.Name = "One");
                    }))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com");

        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
        Assert.StartsWith("One=", transaction.SetCookie[0]);
    }

    [Fact]
    public async Task MapWithSignInOnlyRedirectToReturnUrlOnLoginPath()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Map("/notlogin", signoutApp => signoutApp.Run(context => context.SignInAsync("Cookies",
                            new ClaimsPrincipal(new ClaimsIdentity("whatever")))));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.LoginPath = new PathString("/login"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com/notlogin?ReturnUrl=%2Fpage");
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
        Assert.NotNull(transaction.SetCookie);
    }

    [Fact]
    public async Task MapWillNotAffectSignInRedirectToReturnUrl()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Map("/login", signoutApp => signoutApp.Run(context => context.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity("whatever")))));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.LoginPath = new PathString("/login"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com/login?ReturnUrl=%2Fpage");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        Assert.NotNull(transaction.SetCookie);

        var location = transaction.Response.Headers.Location;
        Assert.Equal("/page", location.OriginalString);
    }

    [Fact]
    public async Task MapWithSignOutOnlyRedirectToReturnUrlOnLogoutPath()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Map("/notlogout", signoutApp => signoutApp.Run(context => context.SignOutAsync("Cookies")));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.LogoutPath = new PathString("/logout"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com/notlogout?ReturnUrl=%2Fpage");
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
        Assert.Contains(".AspNetCore.Cookies=; expires=", transaction.SetCookie[0]);
    }

    [Fact]
    public async Task MapWillNotAffectSignOutRedirectToReturnUrl()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Map("/logout", signoutApp => signoutApp.Run(context => context.SignOutAsync("Cookies")));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.LogoutPath = new PathString("/logout"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var transaction = await server.SendAsync("http://example.com/logout?ReturnUrl=%2Fpage");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        Assert.Contains(".AspNetCore.Cookies=; expires=", transaction.SetCookie[0]);

        var location = transaction.Response.Headers.Location;
        Assert.Equal("/page", location.OriginalString);
    }

    [Fact]
    public async Task MapWillNotAffectAccessDenied()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Map("/forbid", signoutApp => signoutApp.Run(context => context.ForbidAsync("Cookies")));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.AccessDeniedPath = new PathString("/denied"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();
        var transaction = await server.SendAsync("http://example.com/forbid");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);

        var location = transaction.Response.Headers.Location;
        Assert.Equal("/denied", location.LocalPath);
    }

    [Fact]
    public async Task NestedMapWillNotAffectLogin()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                        app.Map("/base", map =>
                        {
                            map.UseAuthentication();
                            map.Map("/login", signoutApp => signoutApp.Run(context => context.ChallengeAsync("Cookies", new AuthenticationProperties() { RedirectUri = "/" })));
                        }))
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.LoginPath = new PathString("/page"))))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();
        var transaction = await server.SendAsync("http://example.com/base/login");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);

        var location = transaction.Response.Headers.Location;
        Assert.Equal("/base/page", location.LocalPath);
        Assert.Equal("?ReturnUrl=%2F", location.Query);
    }

    [Theory]
    [InlineData("/redirect_test", "/loginpath")]
    [InlineData("/redirect_test", "/testpath")]
    [InlineData("http://example.com/redirect_to", "/loginpath")]
    [InlineData("http://example.com/redirect_to", "/testpath")]
    public async Task RedirectUriIsHonoredAfterSignin(string redirectUrl, string loginPath)
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = loginPath;
            o.Cookie.Name = "TestCookie";
        },
        async context =>
            await context.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", CookieAuthenticationDefaults.AuthenticationScheme))),
                new AuthenticationProperties { RedirectUri = redirectUrl })
        );
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath");

        Assert.NotEmpty(transaction.SetCookie);
        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        Assert.Equal(redirectUrl, transaction.Response.Headers.Location.ToString());
    }

    [Fact]
    public async Task RedirectUriInQueryIsIgnoredAfterSigninForUnrecognizedEndpoints()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = "/loginpath";
            o.ReturnUrlParameter = "return";
            o.Cookie.Name = "TestCookie";
        },
        async context =>
        {
            await context.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", CookieAuthenticationDefaults.AuthenticationScheme))));
        });
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath?return=%2Fret_path_2");

        Assert.NotEmpty(transaction.SetCookie);
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
    }

    [Fact]
    public async Task RedirectUriInQueryIsHonoredAfterSignin()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = "/testpath";
            o.ReturnUrlParameter = "return";
            o.Cookie.Name = "TestCookie";
        },
        async context =>
        {
            await context.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", CookieAuthenticationDefaults.AuthenticationScheme))));
        });
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath?return=%2Fret_path_2");

        Assert.NotEmpty(transaction.SetCookie);
        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        Assert.Equal("/ret_path_2", transaction.Response.Headers.Location.ToString());
    }

    [Fact]
    public async Task AbsoluteRedirectUriInQueryStringIsRejected()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = "/testpath";
            o.ReturnUrlParameter = "return";
            o.Cookie.Name = "TestCookie";
        },
        async context =>
        {
            await context.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", CookieAuthenticationDefaults.AuthenticationScheme))));
        });
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath?return=http%3A%2F%2Fexample.com%2Fredirect_to");

        Assert.NotEmpty(transaction.SetCookie);
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
    }

    [Fact]
    public async Task EnsurePrecedenceOfRedirectUriAfterSignin()
    {
        using var host = await CreateHost(o =>
        {
            o.LoginPath = "/testpath";
            o.ReturnUrlParameter = "return";
            o.Cookie.Name = "TestCookie";
        },
        async context =>
        {
            await context.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", CookieAuthenticationDefaults.AuthenticationScheme))),
                new AuthenticationProperties { RedirectUri = "/redirect_test" });
        });
        using var server = host.GetTestServer();
        var transaction = await SendAsync(server, "http://example.com/testpath?return=%2Fret_path_2");

        Assert.NotEmpty(transaction.SetCookie);
        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
        Assert.Equal("/redirect_test", transaction.Response.Headers.Location.ToString());
    }

    [Fact]
    public async Task NestedMapWillNotAffectAccessDenied()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                        app.Map("/base", map =>
                        {
                            map.UseAuthentication();
                            map.Map("/forbid", signoutApp => signoutApp.Run(context => context.ForbidAsync("Cookies")));
                        }))
                        .ConfigureServices(services => services.AddAuthentication().AddCookie(o => o.AccessDeniedPath = new PathString("/denied"))))
            .Build();
        await host.StartAsync();
        using var server = host.GetTestServer();
        var transaction = await server.SendAsync("http://example.com/base/forbid");

        Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);

        var location = transaction.Response.Headers.Location;
        Assert.Equal("/base/denied", location.LocalPath);
    }

    [Fact]
    public async Task CanSpecifyAndShareDataProtector()
    {
        var dp = new NoOpDataProtector();
        using var host1 = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Run((context) =>
                            context.SignInAsync("Cookies",
                                            new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                                            new AuthenticationProperties()));
                    })
                    .ConfigureServices(services => services.AddAuthentication().AddCookie(o =>
                    {
                        o.TicketDataFormat = new TicketDataFormat(dp);
                        o.Cookie.Name = "Cookie";
                    })))
            .Build();
        await host1.StartAsync();
        using var server1 = host1.GetTestServer(); ;

        var transaction = await SendAsync(server1, "http://example.com/stuff");
        Assert.NotNull(transaction.SetCookie);

        using var host2 = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                .Configure(app =>
                {
                    app.UseAuthentication();
                    app.Run(async (context) =>
                    {
                        var result = await context.AuthenticateAsync("Cookies");
                        await DescribeAsync(context.Response, result);
                    });
                })
                .ConfigureServices(services => services.AddAuthentication().AddCookie("Cookies", o =>
                {
                    o.Cookie.Name = "Cookie";
                    o.TicketDataFormat = new TicketDataFormat(dp);
                })))
            .Build();
        await host2.StartAsync();
        using var server2 = host2.GetTestServer();
        var transaction2 = await SendAsync(server2, "http://example.com/stuff", transaction.CookieNameValue);
        Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
    }

    // Issue: https://github.com/aspnet/Security/issues/949
    [Fact]
    public async Task NullExpiresUtcPropertyIsGuarded()
    {
        using var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                .ConfigureServices(services => services.AddAuthentication().AddCookie(o =>
                {
                    o.Events = new CookieAuthenticationEvents
                    {
                        OnValidatePrincipal = context =>
                        {
                            context.Properties.ExpiresUtc = null;
                            context.ShouldRenew = true;
                            return Task.FromResult(0);
                        }
                    };
                }))
                .Configure(app =>
                {
                    app.UseAuthentication();

                    app.Run(async context =>
                    {
                        if (context.Request.Path == "/signin")
                        {
                            await context.SignInAsync(
                                CookieAuthenticationDefaults.AuthenticationScheme,
                                new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))));
                        }
                        else
                        {
                            await context.Response.WriteAsync("ha+1");
                        }
                    });
                }))
            .Build();

        await host.StartAsync();
        using var server = host.GetTestServer();

        var cookie = (await server.SendAsync("http://www.example.com/signin")).SetCookie.FirstOrDefault();
        Assert.NotNull(cookie);

        var transaction = await server.SendAsync("http://www.example.com/", cookie);
        Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode);
    }

    private class NoOpDataProtector : IDataProtector
    {
        public IDataProtector CreateProtector(string purpose)
        {
            return this;
        }

        public byte[] Protect(byte[] plaintext)
        {
            return plaintext;
        }

        public byte[] Unprotect(byte[] protectedData)
        {
            return protectedData;
        }
    }

    private static string FindClaimValue(Transaction transaction, string claimType)
    {
        var claim = transaction.ResponseElement.Elements("claim").SingleOrDefault(elt => elt.Attribute("type").Value == claimType);
        if (claim == null)
        {
            return null;
        }
        return claim.Attribute("value").Value;
    }

    private static string FindPropertiesValue(Transaction transaction, string key)
    {
        var property = transaction.ResponseElement.Elements("extra").SingleOrDefault(elt => elt.Attribute("type").Value == key);
        if (property == null)
        {
            return null;
        }
        return property.Attribute("value").Value;
    }

    private class ClaimsTransformer : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal p)
        {
            var firstId = p.Identities.First();
            if (firstId.HasClaim("marker", "true"))
            {
                firstId.RemoveClaim(firstId.FindFirst("marker"));
            }
            // TransformAsync could be called twice on one request if you have a default scheme and also
            // call AuthenticateAsync.
            if (!p.Identities.Any(i => i.AuthenticationType == "xform"))
            {
                var id = new ClaimsIdentity("xform");
                id.AddClaim(new Claim("xform", "yup"));
                p.AddIdentity(id);
            }
            return Task.FromResult(p);
        }
    }

    private Task<IHost> CreateHost(Action<CookieAuthenticationOptions> configureOptions, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, bool claimsTransform = false)
        => CreateHostWithServices(s =>
        {
            s.AddSingleton<ISystemClock>(_clock);
            s.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(configureOptions);
            if (claimsTransform)
            {
                s.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
            }
        }, testpath, baseAddress);

    private static async Task<IHost> CreateHostWithServices(Action<IServiceCollection> configureServices, Func<HttpContext, Task> testpath = null, Uri baseAddress = null)
    {
        var host = new HostBuilder()
            .ConfigureWebHost(builder =>
                builder.UseTestServer()
                    .Configure(app =>
                    {
                        app.UseAuthentication();
                        app.Use(async (context, next) =>
                        {
                            var req = context.Request;
                            var res = context.Response;
                            PathString remainder;
                            if (req.Path == new PathString("/normal"))
                            {
                                res.StatusCode = 200;
                            }
                            else if (req.Path == new PathString("/forbid")) // Simulate forbidden
                            {
                                await context.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                            }
                            else if (req.Path == new PathString("/challenge"))
                            {
                                await context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                            }
                            else if (req.Path == new PathString("/signinalice"))
                            {
                                await SignInAsAlice(context);
                            }
                            else if (req.Path == new PathString("/signout"))
                            {
                                await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                            }
                            else if (req.Path == new PathString("/unauthorized"))
                            {
                                await context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties());
                            }
                            else if (req.Path == new PathString("/protected/CustomRedirect"))
                            {
                                await context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties() { RedirectUri = "/CustomRedirect" });
                            }
                            else if (req.Path == new PathString("/me"))
                            {
                                await DescribeAsync(res, AuthenticateResult.Success(new AuthenticationTicket(context.User, new AuthenticationProperties(), CookieAuthenticationDefaults.AuthenticationScheme)));
                            }
                            else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder))
                            {
                                var ticket = await context.AuthenticateAsync(remainder.Value.Substring(1));
                                await DescribeAsync(res, ticket);
                            }
                            else if (req.Path == new PathString("/testpath") && testpath != null)
                            {
                                await testpath(context);
                            }
                            else if (req.Path == new PathString("/checkforerrors"))
                            {
                                var result = await context.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); // this used to be "Automatic"
                                if (result.Failure != null)
                                {
                                    throw new Exception("Failed to authenticate", result.Failure);
                                }
                                return;
                            }
                            else
                            {
                                await next(context);
                            }
                        });
                    })
                    .ConfigureServices(configureServices))
            .Build();

        await host.StartAsync();

        var server = host.GetTestServer();
        server.BaseAddress = baseAddress;
        return host;
    }

    private static Task DescribeAsync(HttpResponse res, AuthenticateResult result)
    {
        res.StatusCode = 200;
        res.ContentType = "text/xml";
        var xml = new XElement("xml");
        if (result?.Ticket?.Principal != null)
        {
            xml.Add(result.Ticket.Principal.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value))));
        }
        if (result?.Ticket?.Properties != null)
        {
            xml.Add(result.Ticket.Properties.Items.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value))));
        }
        var xmlBytes = Encoding.UTF8.GetBytes(xml.ToString());
        return res.Body.WriteAsync(xmlBytes, 0, xmlBytes.Length);
    }

    private static async Task<Transaction> SendAsync(TestServer server, string uri, string cookieHeader = null)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, uri);
        if (!string.IsNullOrEmpty(cookieHeader))
        {
            request.Headers.Add("Cookie", cookieHeader);
        }
        var transaction = new Transaction
        {
            Request = request,
            Response = await server.CreateClient().SendAsync(request),
        };
        if (transaction.Response.Headers.Contains("Set-Cookie"))
        {
            transaction.SetCookie = transaction.Response.Headers.GetValues("Set-Cookie").SingleOrDefault();
        }
        if (!string.IsNullOrEmpty(transaction.SetCookie))
        {
            transaction.CookieNameValue = transaction.SetCookie.Split(new[] { ';' }, 2).First();
        }
        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;
    }

    private class Transaction
    {
        public HttpRequestMessage Request { get; set; }
        public HttpResponseMessage Response { get; set; }

        public string SetCookie { get; set; }
        public string CookieNameValue { get; set; }

        public string ResponseText { get; set; }
        public XElement ResponseElement { get; set; }
    }
}