File: SamlSecurityTokenHandler.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (3719 lines) | stat: -rw-r--r-- 172,480 bytes parent folder | download
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
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.IdentityModel.Tokens
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.IdentityModel.Configuration;
    using System.IdentityModel.Diagnostics;
    using System.IdentityModel.Protocols.WSTrust;
    using System.IdentityModel.Selectors;
    using System.IO;
    using System.Linq;
    using System.Runtime;
    using System.Security.Claims;
    using System.Security.Cryptography;
    using System.Security.Principal;
    using System.Text;
    using System.Xml;
    using System.Xml.Schema;
    using Claim = System.Security.Claims.Claim;
    using ClaimTypes = System.Security.Claims.ClaimTypes;

    /// <summary>
    /// This class implements a SecurityTokenHandler for a Saml11 token.  It contains functionality for: Creating, Serializing and Validating 
    /// a Saml 11 Token.
    /// </summary>
    public class SamlSecurityTokenHandler : SecurityTokenHandler
    {
#pragma warning disable 1591
        public const string Namespace = "urn:oasis:names:tc:SAML:1.0";
        public const string BearerConfirmationMethod = Namespace + ":cm:bearer";
        public const string UnspecifiedAuthenticationMethod = Namespace + ":am:unspecified";
        public const string Assertion = Namespace + ":assertion";
#pragma warning restore 1591

        const string Attribute = "saml:Attribute";
        const string Actor = "Actor";
        const string ClaimType2009Namespace = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims";

        // Below are WCF DateTime values for Min and Max. SamlConditions when new'ed up will
        // have these values as default. To maintin compatability with WCF behavior we will 
        // not write out SamlConditions NotBefore and NotOnOrAfter times which match the below
        // values.
        static DateTime WCFMinValue = new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc);
        static DateTime WCFMaxValue = new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc);

        static string[] _tokenTypeIdentifiers = new string[] { SecurityTokenTypes.SamlTokenProfile11, SecurityTokenTypes.OasisWssSamlTokenProfile11 };

        SamlSecurityTokenRequirement _samlSecurityTokenRequirement;

        SecurityTokenSerializer _keyInfoSerializer;

        object _syncObject = new object();

        /// <summary>
        /// Initializes an instance of <see cref="SamlSecurityTokenHandler"/>
        /// </summary>
        public SamlSecurityTokenHandler()
            : this(new SamlSecurityTokenRequirement())
        {
        }

        /// <summary>
        /// Initializes an instance of <see cref="SamlSecurityTokenHandler"/>
        /// </summary>
        /// <param name="samlSecurityTokenRequirement">The SamlSecurityTokenRequirement to be used by the Saml11SecurityTokenHandler instance when validating tokens.</param>
        public SamlSecurityTokenHandler(SamlSecurityTokenRequirement samlSecurityTokenRequirement)
        {
            if (samlSecurityTokenRequirement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSecurityTokenRequirement");
            }
            _samlSecurityTokenRequirement = samlSecurityTokenRequirement;
        }

        /// <summary>
        /// Load custom configuration from Xml
        /// </summary>
        /// <param name="customConfigElements">Custom configuration that describes SamlSecurityTokenRequirement.</param>
        /// <exception cref="ArgumentNullException">Input parameter 'customConfigElements' is null.</exception>
        /// <exception cref="InvalidOperationException">Custom configuration specified was invalid.</exception>
        public override void LoadCustomConfiguration(XmlNodeList customConfigElements)
        {
            if (customConfigElements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("customConfigElements");
            }

            List<XmlElement> configNodes = XmlUtil.GetXmlElements(customConfigElements);

            bool foundValidConfig = false;

            foreach (XmlElement configElement in configNodes)
            {
                if (configElement.LocalName != ConfigurationStrings.SamlSecurityTokenRequirement)
                {
                    continue;
                }

                if (foundValidConfig)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7026, ConfigurationStrings.SamlSecurityTokenRequirement));
                }

                _samlSecurityTokenRequirement = new SamlSecurityTokenRequirement(configElement);

                foundValidConfig = true;
            }

            if (!foundValidConfig)
            {
                _samlSecurityTokenRequirement = new SamlSecurityTokenRequirement();
            }
        }

        #region TokenCreation

        /// <summary>
        /// Creates the security token based on the tokenDescriptor passed in.
        /// </summary>
        /// <param name="tokenDescriptor">The security token descriptor that contains the information to build a token.</param>
        /// <exception cref="ArgumentNullException">Thrown if 'tokenDescriptor' is null.</exception>
        public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            IEnumerable<SamlStatement> statements = CreateStatements(tokenDescriptor);

            // - NotBefore / NotAfter
            // - Audience Restriction
            SamlConditions conditions = CreateConditions(tokenDescriptor.Lifetime, tokenDescriptor.AppliesToAddress, tokenDescriptor);

            SamlAdvice advice = CreateAdvice(tokenDescriptor);

            string issuerName = tokenDescriptor.TokenIssuerName;

            SamlAssertion assertion = CreateAssertion(issuerName, conditions, advice, statements);
            if (assertion == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4013)));
            }

            assertion.SigningCredentials = GetSigningCredentials(tokenDescriptor);

            SecurityToken token = new SamlSecurityToken(assertion);

            //
            // Encrypt the token if encrypting credentials are set
            //

            EncryptingCredentials encryptingCredentials = GetEncryptingCredentials(tokenDescriptor);
            if (encryptingCredentials != null)
            {
                token = new EncryptedSecurityToken(token, encryptingCredentials);
            }

            return token;
        }

        /// <summary>
        /// Gets the credentials for encrypting the token.  Override this method to provide custom encrypting credentials. 
        /// </summary>
        /// <param name="tokenDescriptor">The Scope property provides access to the encrypting credentials.</param>
        /// <returns>The token encrypting credentials.</returns>
        /// <exception cref="ArgumentNullException">Thrown when 'tokenDescriptor' is null.</exception>
        /// <remarks>The default behavior is to return the SecurityTokenDescriptor.Scope.EncryptingCredentials
        /// If this key is ----ymmetric, a symmetric key will be generated and wrapped with the asymmetric key.</remarks>
        protected virtual EncryptingCredentials GetEncryptingCredentials(SecurityTokenDescriptor tokenDescriptor)
        {
            if (null == tokenDescriptor)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            EncryptingCredentials encryptingCredentials = null;

            if (null != tokenDescriptor.EncryptingCredentials)
            {
                encryptingCredentials = tokenDescriptor.EncryptingCredentials;

                if (encryptingCredentials.SecurityKey is AsymmetricSecurityKey)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                        new SecurityTokenException(SR.GetString(SR.ID4178)));
                }
            }

            return encryptingCredentials;
        }

        /// <summary>
        /// Gets the credentials for the signing the assertion.  Override this method to provide custom signing credentials.
        /// </summary>
        /// <param name="tokenDescriptor">The Scope property provides access to the signing credentials.</param>
        /// <exception cref="ArgumentNullException">Thrown when 'tokenDescriptor' is null.</exception>
        /// <returns>The assertion signing credentials.</returns>
        /// <remarks>The default behavior is to return the SecurityTokenDescriptor.Scope.SigningCredentials.</remarks>
        protected virtual SigningCredentials GetSigningCredentials(SecurityTokenDescriptor tokenDescriptor)
        {
            if (null == tokenDescriptor)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            return tokenDescriptor.SigningCredentials;
        }

        /// <summary>
        /// Override this method to provide a SamlAdvice to place in the Samltoken. 
        /// </summary>
        /// <param name="tokenDescriptor">Contains informaiton about the token.</param>
        /// <returns>SamlAdvice, default is null.</returns>
        protected virtual SamlAdvice CreateAdvice(SecurityTokenDescriptor tokenDescriptor)
        {
            return null;
        }

        /// <summary>
        /// Override this method to customize the parameters to create a SamlAssertion. 
        /// </summary>
        /// <param name="issuer">The Issuer of the Assertion.</param>
        /// <param name="conditions">The SamlConditions to add.</param>
        /// <param name="advice">The SamlAdvice to add.</param>
        /// <param name="statements">The SamlStatements to add.</param>
        /// <returns>A SamlAssertion.</returns>
        /// <remarks>A unique random id is created for the assertion
        /// IssueInstance is set to DateTime.UtcNow.</remarks>
        protected virtual SamlAssertion CreateAssertion(string issuer, SamlConditions conditions, SamlAdvice advice, IEnumerable<SamlStatement> statements)
        {
            return new SamlAssertion(System.IdentityModel.UniqueId.CreateRandomId(), issuer, DateTime.UtcNow, conditions, advice, statements);
        }

        /// <summary>
        /// Creates the security token reference when the token is not attached to the message.
        /// </summary>
        /// <param name="token">The saml token.</param>
        /// <param name="attached">Boolean that indicates if a attached or unattached
        /// reference needs to be created.</param>
        /// <returns>A SamlAssertionKeyIdentifierClause.</returns>
        public override SecurityKeyIdentifierClause CreateSecurityTokenReference(SecurityToken token, bool attached)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            return token.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>();
        }

        /// <summary>
        /// Generates all the conditions for saml
        /// 
        /// 1. Lifetime condition
        /// 2. AudienceRestriction condition
        /// 
        /// </summary>
        /// <param name="tokenLifetime">Lifetime of the Token.</param>
        /// <param name="relyingPartyAddress">The endpoint address to who the token is created. The address
        /// is modelled as an AudienceRestriction condition.</param>
        /// <param name="tokenDescriptor">Contains all the other information that is used in token issuance.</param>
        /// <returns>SamlConditions</returns>
        protected virtual SamlConditions CreateConditions(Lifetime tokenLifetime, string relyingPartyAddress, SecurityTokenDescriptor tokenDescriptor)
        {
            SamlConditions conditions = new SamlConditions();
            if (tokenLifetime != null)
            {
                if (tokenLifetime.Created != null)
                {
                    conditions.NotBefore = tokenLifetime.Created.Value;
                }

                if (tokenLifetime.Expires != null)
                {
                    conditions.NotOnOrAfter = tokenLifetime.Expires.Value;
                }
            }

            if (!string.IsNullOrEmpty(relyingPartyAddress))
            {
                conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri(relyingPartyAddress) }));
            }

            return conditions;
        }

        /// <summary>
        /// Generates an enumeration of SamlStatements from a SecurityTokenDescriptor.
        /// Only SamlAttributeStatements and SamlAuthenticationStatements are generated.
        /// Overwrite this method to customize the creation of statements.
        /// <para>
        /// Calls in order (all are virtual):
        /// 1. CreateSamlSubject
        /// 2. CreateAttributeStatements
        /// 3. CreateAuthenticationStatements
        /// </para>
        /// </summary>
        /// <param name="tokenDescriptor">The SecurityTokenDescriptor to use to build the statements.</param>
        /// <returns>An enumeration of SamlStatement.</returns>
        protected virtual IEnumerable<SamlStatement> CreateStatements(SecurityTokenDescriptor tokenDescriptor)
        {
            Collection<SamlStatement> statements = new Collection<SamlStatement>();

            SamlSubject subject = CreateSamlSubject(tokenDescriptor);
            SamlAttributeStatement attributeStatement = CreateAttributeStatement(subject, tokenDescriptor.Subject, tokenDescriptor);
            if (attributeStatement != null)
            {
                statements.Add(attributeStatement);
            }

            SamlAuthenticationStatement authnStatement = CreateAuthenticationStatement(subject, tokenDescriptor.AuthenticationInfo, tokenDescriptor);
            if (authnStatement != null)
            {
                statements.Add(authnStatement);
            }

            return statements;
        }

        /// <summary>
        /// Creates a SamlAuthenticationStatement for each AuthenticationInformation found in AuthenticationInformation. 
        /// Override this method to provide a custom implementation.
        /// </summary>
        /// <param name="samlSubject">The SamlSubject of the Statement.</param>
        /// <param name="authInfo">AuthenticationInformation from which to generate the SAML Authentication statement.</param>
        /// <param name="tokenDescriptor">Contains all the other information that is used in token issuance.</param>
        /// <returns>SamlAuthenticationStatement</returns>
        /// <exception cref="ArgumentNullException">Thrown when 'samlSubject' or 'authInfo' is null.</exception>
        protected virtual SamlAuthenticationStatement CreateAuthenticationStatement(
                                                                SamlSubject samlSubject,
                                                                AuthenticationInformation authInfo,
                                                                SecurityTokenDescriptor tokenDescriptor)
        {
            if (samlSubject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSubject");
            }

            if (tokenDescriptor == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            if (tokenDescriptor.Subject == null)
            {
                return null;
            }
            string authenticationMethod = null;
            string authenticationInstant = null;

            // Search for an Authentication Claim.
            IEnumerable<Claim> claimCollection = (from c in tokenDescriptor.Subject.Claims
                                                  where c.Type == ClaimTypes.AuthenticationMethod
                                                  select c);
            if (claimCollection.Count<Claim>() > 0)
            {
                // We support only one authentication statement and hence we just pick the first authentication type
                // claim found in the claim collection. Since the spec allows multiple Auth Statements 
                // we do not throw an error.
                authenticationMethod = claimCollection.First<Claim>().Value;
            }

            claimCollection = (from c in tokenDescriptor.Subject.Claims
                               where c.Type == ClaimTypes.AuthenticationInstant
                               select c);
            if (claimCollection.Count<Claim>() > 0)
            {
                authenticationInstant = claimCollection.First<Claim>().Value;
            }

            if (authenticationMethod == null && authenticationInstant == null)
            {
                return null;
            }
            else if (authenticationMethod == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4270, "AuthenticationMethod", "SAML11"));
            }
            else if (authenticationInstant == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4270, "AuthenticationInstant", "SAML11"));
            }

            DateTime authInstantTime = DateTime.ParseExact(authenticationInstant,
                                                            DateTimeFormats.Accepted,
                                                            DateTimeFormatInfo.InvariantInfo,
                                                            DateTimeStyles.None).ToUniversalTime();
            if (authInfo == null)
            {
                return new SamlAuthenticationStatement(samlSubject, DenormalizeAuthenticationType(authenticationMethod), authInstantTime, null, null, null);
            }
            else
            {
                return new SamlAuthenticationStatement(samlSubject, DenormalizeAuthenticationType(authenticationMethod), authInstantTime, authInfo.DnsName, authInfo.Address, null);
            }
        }

        /// <summary>
        /// Creates SamlAttributeStatements and adds them to a collection.
        /// Override this method to provide a custom implementation.
        /// <para>
        /// Default behavior is to create a new SamlAttributeStatement for each Subject in the tokenDescriptor.Subjects collection.
        /// </para>
        /// </summary>
        /// <param name="samlSubject">The SamlSubject to use in the SamlAttributeStatement that are created.</param>
        /// <param name="subject">The ClaimsIdentity that contains claims which will be converted to SAML Attributes.</param>
        /// <param name="tokenDescriptor">Contains all the other information that is used in token issuance.</param>
        /// <returns>SamlAttributeStatement</returns>
        /// <exception cref="ArgumentNullException">Thrown when 'samlSubject' is null.</exception>
        protected virtual SamlAttributeStatement CreateAttributeStatement(
            SamlSubject samlSubject,
            ClaimsIdentity subject,
            SecurityTokenDescriptor tokenDescriptor)
        {
            if (subject == null)
            {
                return null;
            }

            if (samlSubject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSubject");
            }

            if (subject.Claims != null)
            {

                List<SamlAttribute> attributes = new List<SamlAttribute>();
                foreach (Claim claim in subject.Claims)
                {
                    if (claim != null && claim.Type != ClaimTypes.NameIdentifier)
                    {
                        //
                        // NameIdentifier claim is already processed while creating the samlsubject
                        // AuthenticationInstant and AuthenticationType are not converted to Claims
                        //
                        switch (claim.Type)
                        {
                            case ClaimTypes.AuthenticationInstant:
                            case ClaimTypes.AuthenticationMethod:
                                break;
                            default:
                                attributes.Add(CreateAttribute(claim, tokenDescriptor));
                                break;
                        }
                    }
                }

                AddDelegateToAttributes(subject, attributes, tokenDescriptor);

                ICollection<SamlAttribute> collectedAttributes = CollectAttributeValues(attributes);
                if (collectedAttributes.Count > 0)
                {
                    return new SamlAttributeStatement(samlSubject, collectedAttributes);
                }
            }

            return null;
        }

        /// <summary>
        /// Collects attributes with a common claim type, claim value type, and original issuer into a
        /// single attribute with multiple values.
        /// </summary>
        /// <param name="attributes">List of attributes generated from claims.</param>
        /// <returns>List of attribute values with common attributes collected into value lists.</returns>
        protected virtual ICollection<SamlAttribute> CollectAttributeValues(ICollection<SamlAttribute> attributes)
        {
            Dictionary<SamlAttributeKeyComparer.AttributeKey, SamlAttribute> distinctAttributes = new Dictionary<SamlAttributeKeyComparer.AttributeKey, SamlAttribute>(attributes.Count, new SamlAttributeKeyComparer());

            foreach (SamlAttribute attribute in attributes)
            {
                SamlAttribute SamlAttribute = attribute as SamlAttribute;
                if (SamlAttribute != null)
                {
                    // Use unique attribute if name, value type, or issuer differ
                    SamlAttributeKeyComparer.AttributeKey attributeKey = new SamlAttributeKeyComparer.AttributeKey(SamlAttribute);

                    if (distinctAttributes.ContainsKey(attributeKey))
                    {
                        foreach (string attributeValue in SamlAttribute.AttributeValues)
                        {
                            distinctAttributes[attributeKey].AttributeValues.Add(attributeValue);
                        }
                    }
                    else
                    {
                        distinctAttributes.Add(attributeKey, SamlAttribute);
                    }
                }
            }

            return distinctAttributes.Values;
        }

        /// <summary>
        /// Adds all the delegates associated with the ActAs subject into the attribute collection.
        /// </summary>
        /// <param name="subject">The delegate of this ClaimsIdentity will be serialized into a SamlAttribute.</param>
        /// <param name="attributes">Attribute collection to which the ActAs token will be serialized.</param>
        /// <param name="tokenDescriptor">Contains all the information that is used in token issuance.</param>
        protected virtual void AddDelegateToAttributes(
            ClaimsIdentity subject,
            ICollection<SamlAttribute> attributes,
            SecurityTokenDescriptor tokenDescriptor)
        {
            if (subject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subject");
            }
            if (tokenDescriptor == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }
            if (subject.Actor == null)
            {
                return;
            }

            List<SamlAttribute> actingAsAttributes = new List<SamlAttribute>();

            foreach (Claim claim in subject.Actor.Claims)
            {
                if (claim != null)
                {
                    actingAsAttributes.Add(CreateAttribute(claim, tokenDescriptor));
                }
            }

            // perform depth first recursion
            AddDelegateToAttributes(subject.Actor, actingAsAttributes, tokenDescriptor);

            ICollection<SamlAttribute> collectedAttributes = CollectAttributeValues(actingAsAttributes);
            attributes.Add(CreateAttribute(new Claim(ClaimTypes.Actor, CreateXmlStringFromAttributes(collectedAttributes), ClaimValueTypes.String), tokenDescriptor));
        }

        /// <summary>
        /// Returns the SamlSubject to use for all the statements that will be created.
        /// Overwrite this method to customize the creation of the SamlSubject.
        /// </summary>
        /// <param name="tokenDescriptor">Contains all the information that is used in token issuance.</param>
        /// <returns>A SamlSubject created from the first subject found in the tokenDescriptor as follows:
        /// <para>
        /// 1. Claim of Type NameIdentifier is searched. If found, SamlSubject.Name is set to claim.Value.
        /// 2. If a non-null tokenDescriptor.proof is found then SamlSubject.KeyIdentifier = tokenDescriptor.Proof.KeyIdentifier AND SamlSubject.ConfirmationMethod is set to 'HolderOfKey'.
        /// 3. If a null tokenDescriptor.proof is found then SamlSubject.ConfirmationMethod is set to 'BearerKey'.
        /// </para>
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when 'tokenDescriptor' is null.</exception>
        protected virtual SamlSubject CreateSamlSubject(SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            SamlSubject samlSubject = new SamlSubject();

            Claim identityClaim = null;
            if (tokenDescriptor.Subject != null && tokenDescriptor.Subject.Claims != null)
            {
                foreach (Claim claim in tokenDescriptor.Subject.Claims)
                {
                    if (claim.Type == ClaimTypes.NameIdentifier)
                    {
                        // Do not allow multiple name identifier claim.
                        if (null != identityClaim)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new InvalidOperationException(SR.GetString(SR.ID4139)));
                        }
                        identityClaim = claim;
                    }
                }
            }

            if (identityClaim != null)
            {
                samlSubject.Name = identityClaim.Value;

                if (identityClaim.Properties.ContainsKey(ClaimProperties.SamlNameIdentifierFormat))
                {
                    samlSubject.NameFormat = identityClaim.Properties[ClaimProperties.SamlNameIdentifierFormat];
                }

                if (identityClaim.Properties.ContainsKey(ClaimProperties.SamlNameIdentifierNameQualifier))
                {
                    samlSubject.NameQualifier = identityClaim.Properties[ClaimProperties.SamlNameIdentifierNameQualifier];
                }
            }

            if (tokenDescriptor.Proof != null)
            {
                //
                // Add the key and the Holder-Of-Key confirmation method
                // for both symmetric and asymmetric key case
                //
                samlSubject.KeyIdentifier = tokenDescriptor.Proof.KeyIdentifier;
                samlSubject.ConfirmationMethods.Add(SamlConstants.HolderOfKey);
            }
            else
            {
                //
                // This is a bearer token
                //
                samlSubject.ConfirmationMethods.Add(BearerConfirmationMethod);
            }

            return samlSubject;
        }

        /// <summary>
        /// Builds an XML formated string from a collection of saml attributes that represend the Actor. 
        /// </summary>
        /// <param name="attributes">An enumeration of Saml Attributes.</param>
        /// <returns>A well formed XML string.</returns>
        /// <remarks>The string is of the form "&lt;Actor&gt;&lt;SamlAttribute name, ns&gt;&lt;SamlAttributeValue&gt;...&lt;/SamlAttributeValue&gt;, ...&lt;/SamlAttribute&gt;...&lt;/Actor&gt;"</remarks>        
        protected virtual string CreateXmlStringFromAttributes(IEnumerable<SamlAttribute> attributes)
        {
            bool actorElementWritten = false;

            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlDictionaryWriter dicWriter = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false))
                {
                    foreach (SamlAttribute samlAttribute in attributes)
                    {
                        if (samlAttribute != null)
                        {
                            if (!actorElementWritten)
                            {
                                dicWriter.WriteStartElement(Actor);
                                actorElementWritten = true;
                            }
                            WriteAttribute(dicWriter, samlAttribute);
                        }
                    }

                    if (actorElementWritten)
                    {
                        dicWriter.WriteEndElement();
                    }

                    dicWriter.Flush();
                }
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        /// <summary>
        /// Generates a SamlAttribute from a claim.
        /// </summary>
        /// <param name="claim">Claim from which to generate a SamlAttribute.</param>
        /// <param name="tokenDescriptor">Contains all the information that is used in token issuance.</param>
        /// <returns>The SamlAttribute.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'claim' is null.</exception>
        protected virtual SamlAttribute CreateAttribute(Claim claim, SecurityTokenDescriptor tokenDescriptor)
        {
            if (claim == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claim");
            }

            int lastSlashIndex = claim.Type.LastIndexOf('/');
            string attributeNamespace = null;
            string attributeName = null;

            if ((lastSlashIndex == 0) || (lastSlashIndex == -1))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claimType", SR.GetString(SR.ID4216, claim.Type));
            }
            else if (lastSlashIndex == claim.Type.Length - 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claimType", SR.GetString(SR.ID4216, claim.Type));
            }
            else
            {
                attributeNamespace = claim.Type.Substring(0, lastSlashIndex);
                //
                // The WCF SamlAttribute requires that the attributeNamespace and attributeName are both non-null and non-empty. 
                // Furthermore, on deserialization / construction it considers the claimType associated with the SamlAttribute to be attributeNamespace + "/" + attributeName. 
                //
                // IDFX extends the WCF SamlAttribute and hence has to work with an attributeNamespace and attributeName that are both non-null and non-empty. 
                // On serialization, we identify the last slash in the claimtype, and treat everything before the slash as the attributeNamespace and everything after the slash as the attributeName. 
                // On deserialization, we don't always insert a "/" between the attributeNamespace and attributeName (like WCF does); we only do so if the attributeNamespace doesn't have a trailing slash.
                //
                // Send     Receive     Behavior
                // =============================
                // WCF      WCF         Works as expected
                //
                // WCF      IDFX        In the common case (http://www.claimtypes.com/foo), WCF will not send a trailing slash in the attributeNamespace. IDFX will add one upon deserialization.
                //                      In the edge case (http://www.claimtypes.com//foo), WCF will send a trailing slash in the attributeNamespace. IDFX will not add one upon deserialization.
                //
                // IDFX     WCF         In the common case (http://www.claimtypes.com/foo), IDFX will not send a trailing slash. WCF will add one upon deserialization.
                //                      In the edge case (http://www.claimtypes.com//foo), IDFX will throw (which is what the fix for FIP 6301 is about).
                //
                // IDFX     IDFX        Works as expected
                //
                if (attributeNamespace.EndsWith("/", StringComparison.Ordinal))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claim", SR.GetString(SR.ID4213, claim.Type));
                }
                attributeName = claim.Type.Substring(lastSlashIndex + 1, claim.Type.Length - (lastSlashIndex + 1));
            }

            SamlAttribute attribute = new SamlAttribute(attributeNamespace, attributeName, new string[] { claim.Value });
            if (!StringComparer.Ordinal.Equals(ClaimsIdentity.DefaultIssuer, claim.OriginalIssuer))
            {
                attribute.OriginalIssuer = claim.OriginalIssuer;
            }
            attribute.AttributeValueXsiType = claim.ValueType;

            return attribute;
        }

        #endregion

        #region TokenValidation

        /// <summary>
        /// Returns value indicates if this handler can validate tokens of type
        /// SamlSecurityToken.
        /// </summary>
        public override bool CanValidateToken
        {
            get { return true; }
        }

        /// <summary>
        /// Gets or sets the X509CeritificateValidator that is used by the current instance.
        /// </summary>
        public X509CertificateValidator CertificateValidator
        {
            get
            {
                if (_samlSecurityTokenRequirement.CertificateValidator == null)
                {
                    if (Configuration != null)
                    {
                        return Configuration.CertificateValidator;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return _samlSecurityTokenRequirement.CertificateValidator;
                }
            }
            set
            {
                _samlSecurityTokenRequirement.CertificateValidator = value;
            }
        }

        /// <summary>
        /// Throws if a token is detected as being replayed. If the token is not found it is added to the <see cref="TokenReplayCache" />.
        /// </summary>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="InvalidOperationException">Configuration or Configuration.TokenReplayCache property is null.</exception>
        /// <exception cref="ArgumentException">The input argument 'token' is not a SamlSecurityToken.</exception>
        /// <exception cref="SecurityTokenValidationException">SamlSecurityToken.Assertion.Id is null or empty.</exception>
        /// <exception cref="SecurityTokenReplayDetectedException">If the token is found in the <see cref="TokenReplayCache" />.</exception>
        /// <remarks>The default behavior is to only check tokens bearer tokens (tokens that do not have keys).</remarks>
        protected override void DetectReplayedToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SamlSecurityToken samlToken = token as SamlSecurityToken;
            if (null == samlToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1067, token.GetType().ToString()));
            }

            //
            // by default we only check bearer tokens.
            //

            if (samlToken.SecurityKeys.Count != 0)
            {
                return;
            }

            if (Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (Configuration.Caches.TokenReplayCache == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4278));
            }

            if (string.IsNullOrEmpty(samlToken.Assertion.AssertionId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID1063)));
            }

            StringBuilder stringBuilder = new StringBuilder();

            string key;

            using (HashAlgorithm hashAlgorithm = CryptoHelper.NewSha256HashAlgorithm())
            {
                if (string.IsNullOrEmpty(samlToken.Assertion.Issuer))
                {
                    stringBuilder.AppendFormat("{0}{1}", samlToken.Assertion.AssertionId, _tokenTypeIdentifiers[0]);
                }
                else
                {
                    stringBuilder.AppendFormat("{0}{1}{2}", samlToken.Assertion.AssertionId, samlToken.Assertion.Issuer, _tokenTypeIdentifiers[0]);
                }

                key = Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())));
            }

            if (Configuration.Caches.TokenReplayCache.Contains(key))
            {
                if (string.IsNullOrEmpty(samlToken.Assertion.Issuer))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                             new SecurityTokenReplayDetectedException(SR.GetString(SR.ID1062, typeof(SamlSecurityToken).ToString(), samlToken.Assertion.AssertionId, "")));
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new SecurityTokenReplayDetectedException(SR.GetString(SR.ID1062, typeof(SamlSecurityToken).ToString(), samlToken.Assertion.AssertionId, samlToken.Assertion.Issuer)));
                }
            }
            else
            {
                Configuration.Caches.TokenReplayCache.AddOrUpdate(key, token, DateTimeUtil.Add(GetTokenReplayCacheEntryExpirationTime(samlToken), Configuration.MaxClockSkew));
            }
        }

        /// <summary>
        /// Returns the time until which the token should be held in the token replay cache.
        /// </summary>
        /// <param name="token">The token to return an expiration time for.</param>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="SecurityTokenValidationException">The SamlSecurityToken's validity period is greater than the expiration period set to TokenReplayCache.</exception>
        /// <returns>A DateTime representing the expiration time.</returns>
        protected virtual DateTime GetTokenReplayCacheEntryExpirationTime(SamlSecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            //
            //  DateTimeUtil handles overflows
            //
            DateTime maximumExpirationTime = DateTimeUtil.Add(DateTime.UtcNow, Configuration.TokenReplayCacheExpirationPeriod);

            // If the token validity period is greater than the TokenReplayCacheExpirationPeriod, throw
            if (DateTime.Compare(maximumExpirationTime, token.ValidTo) < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new SecurityTokenValidationException(SR.GetString(SR.ID1069, token.ValidTo.ToString(), Configuration.TokenReplayCacheExpirationPeriod.ToString())));
            }

            return token.ValidTo;
        }

        /// <summary>
        /// Rejects tokens that are not valid. 
        /// </summary>
        /// <remarks>
        /// The token may be invalid for a number of reasons. For example, the 
        /// current time may not be within the token's validity period, the 
        /// token may contain invalid or contradictory data, or the token 
        /// may contain unsupported SAML elements.
        /// </remarks>
        /// <param name="conditions">SAML condition to be validated.</param>
        /// <param name="enforceAudienceRestriction">True to check for Audience Restriction condition.</param>
        protected virtual void ValidateConditions(SamlConditions conditions, bool enforceAudienceRestriction)
        {
            if (null != conditions)
            {
                DateTime now = DateTime.UtcNow;

                if (null != conditions.NotBefore
                    && DateTimeUtil.Add(now, Configuration.MaxClockSkew) < conditions.NotBefore)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityTokenNotYetValidException(SR.GetString(SR.ID4222, conditions.NotBefore, now)));
                }

                if (null != conditions.NotOnOrAfter
                    && DateTimeUtil.Add(now, Configuration.MaxClockSkew.Negate()) >= conditions.NotOnOrAfter)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityTokenExpiredException(SR.GetString(SR.ID4223, conditions.NotOnOrAfter, now)));
                }
            }

            //
            // Enforce the audience restriction
            //
            if (enforceAudienceRestriction)
            {
                if (this.Configuration == null || this.Configuration.AudienceRestriction.AllowedAudienceUris.Count == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID1032)));
                }

                //
                // Process each condition, enforcing the AudienceRestrictionConditions
                //
                bool foundAudienceRestriction = false;

                if (null != conditions && null != conditions.Conditions)
                {
                    foreach (SamlCondition condition in conditions.Conditions)
                    {
                        SamlAudienceRestrictionCondition audienceRestriction = condition as SamlAudienceRestrictionCondition;
                        if (null == audienceRestriction)
                        {
                            // Skip other conditions
                            continue;
                        }

                        _samlSecurityTokenRequirement.ValidateAudienceRestriction(this.Configuration.AudienceRestriction.AllowedAudienceUris, audienceRestriction.Audiences);
                        foundAudienceRestriction = true;
                    }
                }

                if (!foundAudienceRestriction)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(SR.GetString(SR.ID1035)));
                }
            }
        }

        /// <summary>
        /// Validates a <see cref="SamlSecurityToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SamlSecurityToken"/> to validate.</param>
        /// <returns>The <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception>
        /// <exception cref="ArgumentException">The token is not assignable from <see cref="SamlSecurityToken"/>.</exception>
        /// <exception cref="InvalidOperationException">Configuration <see cref="SecurityTokenHandlerConfiguration"/>is null.</exception>
        /// <exception cref="ArgumentException">SamlSecurityToken.Assertion is null.</exception>
        /// <exception cref="SecurityTokenValidationException">Thrown if SamlSecurityToken.Assertion.SigningToken is null.</exception>
        /// <exception cref="SecurityTokenValidationException">Thrown if the certificate associated with the token issuer does not pass validation.</exception>
        public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SamlSecurityToken samlToken = token as SamlSecurityToken;
            if (samlToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1033, token.GetType().ToString()));
            }

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            try
            {
                if (samlToken.Assertion == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID1034));
                }

                TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString(SR.TraceValidateToken), new SecurityTraceRecordHelper.TokenTraceRecord(token), null, null);

                // Ensure token was signed and verified at some point
                if (samlToken.Assertion.SigningToken == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID4220)));
                }

                this.ValidateConditions(samlToken.Assertion.Conditions, _samlSecurityTokenRequirement.ShouldEnforceAudienceRestriction(this.Configuration.AudienceRestriction.AudienceMode, samlToken));

                // We need something like AudienceUriMode and have a setting on Configuration to allow extensibility and custom settings
                // By default we only check bearer tokens
                if (this.Configuration.DetectReplayedTokens)
                {
                    this.DetectReplayedToken(samlToken);
                }

                //
                // If the backing token is x509, validate trust
                //
                X509SecurityToken x509IssuerToken = samlToken.Assertion.SigningToken as X509SecurityToken;
                if (x509IssuerToken != null)
                {
                    try
                    {
                        CertificateValidator.Validate(x509IssuerToken.Certificate);
                    }
                    catch (SecurityTokenValidationException e)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID4257,
                                X509Util.GetCertificateId(x509IssuerToken.Certificate)), e));
                    }
                }

                //
                // Create the claims
                //
                ClaimsIdentity claimsIdentity = CreateClaims(samlToken);

                if (_samlSecurityTokenRequirement.MapToWindows)
                {
                    // TFS: 153865, [....] WindowsIdentity does not set Authtype. I don't think that authtype should be set here anyway.
                    // The authtype will be S4U (kerberos) it doesn't really matter that the upn arrived in a SAML token.
                    WindowsIdentity windowsIdentity = CreateWindowsIdentity(FindUpn(claimsIdentity));

                    // PARTIAL TRUST: will fail when adding claims, AddClaims is SecurityCritical.
                    windowsIdentity.AddClaims(claimsIdentity.Claims);
                    claimsIdentity = windowsIdentity;
                }

                if (this.Configuration.SaveBootstrapContext)
                {
                    claimsIdentity.BootstrapContext = new BootstrapContext(token, this);
                }

                this.TraceTokenValidationSuccess(token);

                List<ClaimsIdentity> identities = new List<ClaimsIdentity>(1);
                identities.Add(claimsIdentity);
                return identities.AsReadOnly();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                this.TraceTokenValidationFailure(token, e.Message);
                throw e;
            }
        }

        /// <summary>
        /// Creates a <see cref="WindowsIdentity"/> object using the <paramref name="upn"/> value.
        /// </summary>
        /// <param name="upn">The upn name.</param>
        /// <returns>A <see cref="WindowsIdentity"/> object.</returns>
        /// <exception cref="ArgumentException">If <paramref name="upn"/> is null or empty.</exception>
        protected virtual WindowsIdentity CreateWindowsIdentity(string upn)
        {
            if (string.IsNullOrEmpty(upn))
            {
                throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("upn");
            }

            WindowsIdentity wi = new WindowsIdentity(upn);

            return new WindowsIdentity(wi.Token, AuthenticationTypes.Federation, WindowsAccountType.Normal, true);
        }
        
        /// <summary>
        /// Finds the UPN claim value in the provided <see cref="ClaimsIdentity" /> object for the purpose
        /// of mapping the identity to a <see cref="WindowsIdentity" /> object.
        /// </summary>
        /// <param name="claimsIdentity">The claims identity object containing the desired UPN claim.</param>
        /// <returns>The UPN claim value found.</returns>
        /// <exception cref="InvalidOperationException">If more than one UPN claim is contained in 
        /// <paramref name="claimsIdentity"/></exception>
        protected virtual string FindUpn(ClaimsIdentity claimsIdentity)
        {
            return ClaimsHelper.FindUpn(claimsIdentity);
        }

        /// <summary>
        /// Generates SubjectCollection that represents a SamlToken.
        /// Only SamlAttributeStatements processed.
        /// Overwrite this method to customize the creation of statements.
        /// <para>
        /// Calls:
        /// 1. ProcessAttributeStatement for SamlAttributeStatements.
        /// 2. ProcessAuthenticationStatement for SamlAuthenticationStatements.
        /// 3. ProcessAuthorizationDecisionStatement for SamlAuthorizationDecisionStatements.
        /// 4. ProcessCustomStatement for other SamlStatements.
        /// </para>
        /// </summary>
        /// <param name="samlSecurityToken">The token used to generate the SubjectCollection.</param>
        /// <returns>ClaimsIdentity representing the subject of the SamlToken.</returns>
        /// <exception cref="ArgumentNullException">Thrown if 'samlSecurityToken' is null.</exception>
        protected virtual ClaimsIdentity CreateClaims(SamlSecurityToken samlSecurityToken)
        {
            if (samlSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSecurityToken");
            }

            if (samlSecurityToken.Assertion == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("samlSecurityToken", SR.GetString(SR.ID1034));
            }

            //
            // Construct the subject and issuer identities.
            // Use claim types specified in the security token requirements used for IPrincipal.Role and IIdentity.Name 
            //
            ClaimsIdentity subject = new ClaimsIdentity(AuthenticationTypes.Federation,
                                                         _samlSecurityTokenRequirement.NameClaimType,
                                                         _samlSecurityTokenRequirement.RoleClaimType);

            string issuer = null;

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (this.Configuration.IssuerNameRegistry == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4277));
            }

            // SamlAssertion. The SigningToken may or may not be null.
            // The default IssuerNameRegistry will throw if null.
            // This callout is provided for extensibility scenarios with custom IssuerNameRegistry.
            issuer = this.Configuration.IssuerNameRegistry.GetIssuerName(samlSecurityToken.Assertion.SigningToken, samlSecurityToken.Assertion.Issuer);

            if (string.IsNullOrEmpty(issuer))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4175)));
            }

            ProcessStatement(samlSecurityToken.Assertion.Statements, subject, issuer);
            return subject;
        }

        /// <summary>
        /// Returns the Saml11 AuthenticationMethod matching a normalized value.
        /// </summary>
        /// <param name="normalizedAuthenticationType">Normalized value.</param>
        /// <returns><see cref="SamlConstants.AuthenticationMethods"/></returns>
        protected virtual string DenormalizeAuthenticationType(string normalizedAuthenticationType)
        {
            return AuthenticationTypeMaps.Denormalize(normalizedAuthenticationType, AuthenticationTypeMaps.Saml);
        }

        /// <summary>
        /// Returns the normalized value matching a Saml11 AuthenticationMethod.
        /// </summary>
        /// <param name="saml11AuthenticationMethod"><see cref="SamlConstants.AuthenticationMethods"/></param>
        /// <returns>Normalized value.</returns>
        protected virtual string NormalizeAuthenticationType(string saml11AuthenticationMethod)
        {
            return AuthenticationTypeMaps.Normalize(saml11AuthenticationMethod, AuthenticationTypeMaps.Saml);
        }

        /// <summary>
        /// Processes all statements to generate claims.
        /// </summary>
        /// <param name="statements">A collection of Saml2Statement.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="issuer">The issuer.</param>
        protected virtual void ProcessStatement(IList<SamlStatement> statements, ClaimsIdentity subject, string issuer)
        {
            if (statements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statements");
            }

            Collection<SamlAuthenticationStatement> authStatementCollection = new Collection<SamlAuthenticationStatement>();

            //
            // Validate that the Saml subjects in all the statements are the same.
            //
            ValidateStatements(statements);

            foreach (SamlStatement samlStatement in statements)
            {
                SamlAttributeStatement attrStatement = samlStatement as SamlAttributeStatement;
                if (attrStatement != null)
                {
                    ProcessAttributeStatement(attrStatement, subject, issuer);
                }
                else
                {
                    SamlAuthenticationStatement authenStatement = samlStatement as SamlAuthenticationStatement;
                    if (authenStatement != null)
                    {
                        authStatementCollection.Add(authenStatement);
                    }
                    else
                    {
                        SamlAuthorizationDecisionStatement decisionStatement = samlStatement as SamlAuthorizationDecisionStatement;
                        if (decisionStatement != null)
                        {
                            ProcessAuthorizationDecisionStatement(decisionStatement, subject, issuer);
                        }
                        else
                        {
                            // We don't process custom statements. Just fall through.
                        }
                    }
                }
            }

            // Processing Authentication statement(s) should be done at the last phase to add the authentication
            // information as claims to the ClaimsIdentity
            foreach (SamlAuthenticationStatement authStatement in authStatementCollection)
            {
                if (authStatement != null)
                {
                    ProcessAuthenticationStatement(authStatement, subject, issuer);
                }
            }
        }

        /// <summary>
        /// Override this virtual to provide custom processing of SamlAttributeStatements.
        /// </summary>
        /// <param name="samlStatement">The SamlAttributeStatement to process.</param>
        /// <param name="subject">The identity that should be modified to reflect the statement.</param>
        /// <param name="issuer">The subject that identifies the issuer.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'samlStatement' or 'subject' is null.</exception>
        protected virtual void ProcessAttributeStatement(SamlAttributeStatement samlStatement, ClaimsIdentity subject, string issuer)
        {
            if (samlStatement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatement");
            }

            if (subject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subject");
            }

            // We will be adding the nameid claim only once for multiple attribute and/or authn statements. 
            // As of now, we put the nameId claim both inside the saml subject and the saml attribute statement as assertion. 
            // When generating claims, we will only pick up the saml subject of a saml statement, not the attribute statement value.
            ProcessSamlSubject(samlStatement.SamlSubject, subject, issuer);

            foreach (SamlAttribute attr in samlStatement.Attributes)
            {
                string claimType = null;
                if (string.IsNullOrEmpty(attr.Namespace))
                {
                    claimType = attr.Name;
                }
                else if (StringComparer.Ordinal.Equals(attr.Name, SamlConstants.ElementNames.NameIdentifier))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4094)));
                }
                else
                {
                    // check if Namespace end with slash don't add it
                    // If no slash or last char is not a slash, add it.
                    int lastSlashIndex = attr.Namespace.LastIndexOf('/');
                    if ((lastSlashIndex == -1) || (!(lastSlashIndex == attr.Namespace.Length - 1)))
                    {
                        claimType = attr.Namespace + "/" + attr.Name;
                    }
                    else
                    {
                        claimType = attr.Namespace + attr.Name;
                    }

                }

                if (claimType == ClaimTypes.Actor)
                {
                    if (subject.Actor != null)
                    {
                        throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4034));
                    }

                    SetDelegateFromAttribute(attr, subject, issuer);
                }
                else
                {
                    for (int k = 0; k < attr.AttributeValues.Count; ++k)
                    {
                        // Check if we already have a nameId claim.
                        if (StringComparer.Ordinal.Equals(ClaimTypes.NameIdentifier, claimType) && GetClaim(subject, ClaimTypes.NameIdentifier) != null)
                        {
                            continue;
                        }
                        string originalIssuer = issuer;
                        SamlAttribute SamlAttribute = attr as SamlAttribute;
                        if ((SamlAttribute != null) && (SamlAttribute.OriginalIssuer != null))
                        {
                            originalIssuer = SamlAttribute.OriginalIssuer;
                        }
                        string claimValueType = ClaimValueTypes.String;
                        if (SamlAttribute != null)
                        {
                            claimValueType = SamlAttribute.AttributeValueXsiType;
                        }
                        subject.AddClaim(new Claim(claimType, attr.AttributeValues[k], claimValueType, issuer, originalIssuer));
                    }
                }
            }

        }

        /// <summary>
        /// Gets a specific claim of type claimType from the subject's claims collection.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="claimType">The type of the claim.</param>
        /// <returns>The claim of type claimType if present, else null.</returns>
        private static Claim GetClaim(ClaimsIdentity subject, string claimType)
        {
            foreach (Claim claim in subject.Claims)
            {
                if (StringComparer.Ordinal.Equals(claimType, claim.Type))
                {
                    return claim;
                }
            }
            return null;
        }

        /// <summary>
        /// For each saml statement (attribute/authentication/authz/custom), we will check if we need to create
        /// a nameid claim or a key identifier claim out of its SamlSubject.
        /// </summary>
        /// <remarks>
        /// To make sure that the saml subject within each saml statement are the same, this method does the following comparisons.
        /// 1. All the saml subjects' contents are the same.
        /// 2. The name identifiers (if present) are the same. The name identifier comparison is done for the name identifier value,
        ///    name identifier format (if present), and name identifier qualifier (if present).
        /// 3. The key identifiers (if present) are the same.
        /// </remarks>
        /// <param name="samlSubject">The SamlSubject to extract claims from.</param>
        /// <param name="subject">The identity that should be modified to reflect the SamlSubject.</param>
        /// <param name="issuer">The Issuer claims of the SAML token.</param>
        /// <exception cref="ArgumentNullException">The parameter 'samlSubject' is null.</exception>
        protected virtual void ProcessSamlSubject(SamlSubject samlSubject, ClaimsIdentity subject, string issuer)
        {
            if (samlSubject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSubject");
            }

            Claim nameIdentifierClaim = GetClaim(subject, ClaimTypes.NameIdentifier);

            if (nameIdentifierClaim == null)
            {
                // first saml subject. so we will create claims for this subject.
                // subsequent subjects must have the same content.

                // add name identifier claim if present.
                if (!string.IsNullOrEmpty(samlSubject.Name))
                {
                    Claim claim = new Claim(ClaimTypes.NameIdentifier, samlSubject.Name, ClaimValueTypes.String, issuer);

                    if (samlSubject.NameFormat != null)
                    {
                        claim.Properties[ClaimProperties.SamlNameIdentifierFormat] = samlSubject.NameFormat;
                    }

                    if (samlSubject.NameQualifier != null)
                    {
                        claim.Properties[ClaimProperties.SamlNameIdentifierNameQualifier] = samlSubject.NameQualifier;
                    }

                    subject.AddClaim(claim);
                }
            }
        }

        /// <summary>
        /// Override this virtual to provide custom processing of the SamlAuthenticationStatement.
        /// By default it adds authentication type and instant to each claim.
        /// </summary>
        /// <param name="samlStatement">The SamlAuthenticationStatement to process</param>
        /// <param name="subject">The identity that should be modified to reflect the statement</param>
        /// <param name="issuer">issuer Identity.</param>
        /// <exception cref="ArgumentNullException">The parameter 'samlSubject' or 'subject' is null.</exception>
        protected virtual void ProcessAuthenticationStatement(SamlAuthenticationStatement samlStatement, ClaimsIdentity subject, string issuer)
        {
            if (samlStatement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatement");
            }

            if (subject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subject");
            }

            // When there is only a authentication statement present inside a saml assertion, we need to generate
            // a nameId claim. See FIP 4848. We do not support any saml assertion without a attribute statement, but
            // we might receive a saml assertion with only a authentication statement.
            ProcessSamlSubject(samlStatement.SamlSubject, subject, issuer);

            subject.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, NormalizeAuthenticationType(samlStatement.AuthenticationMethod), ClaimValueTypes.String, issuer));
            subject.AddClaim(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(samlStatement.AuthenticationInstant.ToUniversalTime(), DateTimeFormats.Generated), ClaimValueTypes.DateTime, issuer));
        }

        /// <summary>
        /// Override this virtual to provide custom processing of SamlAuthorizationDecisionStatement.
        /// By default no processing is performed, you will need to access the token for SamlAuthorizationDecisionStatement information.
        /// </summary>
        /// <param name="samlStatement">The SamlAuthorizationDecisionStatement to process.</param>
        /// <param name="subject">The identity that should be modified to reflect the statement.</param>
        /// <param name="issuer">The subject that identifies the issuer.</param>
        protected virtual void ProcessAuthorizationDecisionStatement(SamlAuthorizationDecisionStatement samlStatement, ClaimsIdentity subject, string issuer)
        {
        }

        /// <summary>
        /// This method gets called when a special type of SamlAttribute is detected. The SamlAttribute passed in wraps a SamlAttribute 
        /// that contains a collection of AttributeValues, each of which are mapped to a claim.  All of the claims will be returned
        /// in an ClaimsIdentity with the specified issuer.
        /// </summary>
        /// <param name="attribute">The SamlAttribute to be processed.</param>
        /// <param name="subject">The identity that should be modified to reflect the SamlAttribute.</param>
        /// <param name="issuer">Issuer Identity.</param>
        /// <exception cref="InvalidOperationException">Will be thrown if the SamlAttribute does not contain any valid SamlAttributeValues.</exception>
        protected virtual void SetDelegateFromAttribute(SamlAttribute attribute, ClaimsIdentity subject, string issuer)
        {
            // bail here nothing to add.
            if (subject == null || attribute == null || attribute.AttributeValues == null || attribute.AttributeValues.Count < 1)
            {
                return;
            }

            Collection<Claim> claims = new Collection<Claim>();
            SamlAttribute actingAsAttribute = null;

            foreach (string attributeValue in attribute.AttributeValues)
            {
                if (attributeValue != null && attributeValue.Length > 0)
                {

                    using (XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(attributeValue), XmlDictionaryReaderQuotas.Max))
                    {
                        xmlReader.MoveToContent();
                        xmlReader.ReadStartElement(Actor);

                        while (xmlReader.IsStartElement(Attribute))
                        {
                            SamlAttribute innerAttribute = ReadAttribute(xmlReader);
                            if (innerAttribute != null)
                            {
                                string claimType = string.IsNullOrEmpty(innerAttribute.Namespace) ? innerAttribute.Name : innerAttribute.Namespace + "/" + innerAttribute.Name;
                                if (claimType == ClaimTypes.Actor)
                                {
                                    // In this case we have two delegates acting as an identity, we do not allow this
                                    if (actingAsAttribute != null)
                                    {
                                        throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4034));
                                    }

                                    actingAsAttribute = innerAttribute;
                                }
                                else
                                {
                                    string claimValueType = ClaimValueTypes.String;
                                    string originalIssuer = null;
                                    SamlAttribute SamlAttribute = innerAttribute as SamlAttribute;
                                    if (SamlAttribute != null)
                                    {
                                        claimValueType = SamlAttribute.AttributeValueXsiType;
                                        originalIssuer = SamlAttribute.OriginalIssuer;
                                    }
                                    for (int k = 0; k < innerAttribute.AttributeValues.Count; ++k)
                                    {
                                        Claim claim = null;
                                        if (string.IsNullOrEmpty(originalIssuer))
                                        {
                                            claim = new Claim(claimType, innerAttribute.AttributeValues[k], claimValueType, issuer);
                                        }
                                        else
                                        {
                                            claim = new Claim(claimType, innerAttribute.AttributeValues[k], claimValueType, issuer, originalIssuer);
                                        }
                                        claims.Add(claim);
                                    }
                                }
                            }
                        }

                        xmlReader.ReadEndElement(); // Actor
                    }
                }
            }

            subject.Actor = new ClaimsIdentity(claims, AuthenticationTypes.Federation);

            SetDelegateFromAttribute(actingAsAttribute, subject.Actor, issuer);
        }

        #endregion

        #region TokenSerialization

        /// <summary>
        /// Indicates whether the current XML element can be read as a token 
        /// of the type handled by this instance.
        /// </summary>
        /// <param name="reader">An XML reader positioned at a start 
        /// element. The reader should not be advanced.</param>
        /// <returns>'True' if the ReadToken method can the element.</returns>
        public override bool CanReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                return false;
            }

            return reader.IsStartElement(SamlConstants.ElementNames.Assertion, SamlConstants.Namespace);
        }

        /// <summary>
        /// Deserializes from XML a token of the type handled by this instance.
        /// </summary>
        /// <param name="reader">An XML reader positioned at the token's start 
        /// element.</param>
        /// <returns>An instance of <see cref="SamlSecurityToken"/>.</returns>
        /// <exception cref="InvalidOperationException">Is thrown if 'Configuration' or 'Configruation.IssuerTokenResolver' is null.</exception>
        public override SecurityToken ReadToken(XmlReader reader)
        {
            if (Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (Configuration.IssuerTokenResolver == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4275));
            }

            SamlAssertion assertion = ReadAssertion(reader);
            //
            // Resolve signing token if one is present. It may be deferred and signed by reference.
            //
            SecurityToken token;

            TryResolveIssuerToken(assertion, Configuration.IssuerTokenResolver, out token);

            assertion.SigningToken = token;

            return new SamlSecurityToken(assertion);
        }

        /// <summary>
        /// Read saml:Action element.
        /// </summary>
        /// <param name="reader">XmlReader positioned at saml:Action element.</param>
        /// <returns>SamlAction</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The saml:Action element contains unknown elements.</exception>
        protected virtual SamlAction ReadAction(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (reader.IsStartElement(SamlConstants.ElementNames.Action, SamlConstants.Namespace))
            {
                // The Namespace attribute is optional.
                string ns = reader.GetAttribute(SamlConstants.AttributeNames.Namespace, null);

                reader.MoveToContent();
                string action = reader.ReadString();
                if (string.IsNullOrEmpty(action))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4073)));
                }

                reader.MoveToContent();
                reader.ReadEndElement();

                return new SamlAction(action, ns);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4065, SamlConstants.ElementNames.Action, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }
        }

        /// <summary>
        /// Writes the given SamlAction to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlAction into.</param>
        /// <param name="action">SamlAction to serialize.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'action' is null.</exception>
        protected virtual void WriteAction(XmlWriter writer, SamlAction action)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (action == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("action");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Action, SamlConstants.Namespace);
            if (!string.IsNullOrEmpty(action.Namespace))
            {
                writer.WriteAttributeString(SamlConstants.AttributeNames.Namespace, null, action.Namespace);
            }
            writer.WriteString(action.Action);
            writer.WriteEndElement();
        }

        /// <summary>
        /// Read saml:Advice element from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a SAML Advice element.</param>
        /// <returns>SamlAdvice</returns>
        /// <exception cref="ArgumentNullException">Parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The reder is not positioned at a saml:Advice element.</exception>
        protected virtual SamlAdvice ReadAdvice(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.Advice, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4065, SamlConstants.ElementNames.Advice, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            // SAML Advice is an optional element and all its child elements are optional 
            // too. So we may have an empty saml:Advice element in the saml token.
            if (reader.IsEmptyElement)
            {
                // Just issue a read for the empty element.
                reader.MoveToContent();
                reader.Read();
                return new SamlAdvice();
            }

            reader.MoveToContent();
            reader.Read();
            Collection<string> assertionIdReferences = new Collection<string>();
            Collection<SamlAssertion> assertions = new Collection<SamlAssertion>();
            while (reader.IsStartElement())
            {

                if (reader.IsStartElement(SamlConstants.ElementNames.AssertionIdReference, SamlConstants.Namespace))
                {
                    assertionIdReferences.Add(reader.ReadString());
                    reader.ReadEndElement();
                }
                else if (reader.IsStartElement(SamlConstants.ElementNames.Assertion, SamlConstants.Namespace))
                {
                    SamlAssertion assertion = ReadAssertion(reader);
                    assertions.Add(assertion);
                }
                else
                {
                    TraceUtility.TraceString(TraceEventType.Warning, SR.GetString(SR.ID8005, reader.LocalName, reader.NamespaceURI));
                    reader.Skip();
                }

            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return new SamlAdvice(assertionIdReferences, assertions);
        }


        /// <summary>
        /// Serialize the given SamlAdvice to the given XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlAdvice.</param>
        /// <param name="advice">SamlAdvice to be serialized.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'advice' is null.</exception>
        protected virtual void WriteAdvice(XmlWriter writer, SamlAdvice advice)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (advice == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("advice");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Advice, SamlConstants.Namespace);
            if (advice.AssertionIdReferences.Count > 0)
            {
                foreach (string assertionIdReference in advice.AssertionIdReferences)
                {
                    if (string.IsNullOrEmpty(assertionIdReference))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4079)));
                    }
                    writer.WriteElementString(SamlConstants.Prefix, SamlConstants.ElementNames.AssertionIdReference, SamlConstants.Namespace, assertionIdReference);
                }
            }

            if (advice.Assertions.Count > 0)
            {
                foreach (SamlAssertion assertion in advice.Assertions)
                {
                    WriteAssertion(writer, assertion);
                }
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read saml:Assertion element from the given reader.
        /// </summary>
        /// <param name="reader">XmlReader to deserialize the Assertion from.</param>
        /// <returns>SamlAssertion</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at a saml:Assertion element or the Assertion
        /// contains unknown child elements.</exception>
        protected virtual SamlAssertion ReadAssertion(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (this.Configuration.IssuerTokenResolver == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4275));
            }

            SamlAssertion assertion = new SamlAssertion();

            EnvelopedSignatureReader wrappedReader = new EnvelopedSignatureReader(reader, new WrappedSerializer(this, assertion), this.Configuration.IssuerTokenResolver, false, true, false);


            if (!wrappedReader.IsStartElement(SamlConstants.ElementNames.Assertion, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4065, SamlConstants.ElementNames.Assertion, SamlConstants.Namespace, wrappedReader.LocalName, wrappedReader.NamespaceURI)));
            }

            string attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.MajorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.MajorVersion)));
            }

            int majorVersion = XmlConvert.ToInt32(attributeValue);

            attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.MinorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.MinorVersion)));
            }

            int minorVersion = XmlConvert.ToInt32(attributeValue);

            if ((majorVersion != SamlConstants.MajorVersionValue) || (minorVersion != SamlConstants.MinorVersionValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4076, majorVersion, minorVersion, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue)));
            }

            attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.AssertionId, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.AssertionId)));
            }

            if (!XmlUtil.IsValidXmlIDValue(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4077, attributeValue)));
            }

            assertion.AssertionId = attributeValue;

            attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.Issuer, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.Issuer)));
            }

            assertion.Issuer = attributeValue;

            attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.IssueInstant, null);
            if (!string.IsNullOrEmpty(attributeValue))
            {
                assertion.IssueInstant = DateTime.ParseExact(
                    attributeValue, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            wrappedReader.MoveToContent();
            wrappedReader.Read();

            if (wrappedReader.IsStartElement(SamlConstants.ElementNames.Conditions, SamlConstants.Namespace))
            {
                assertion.Conditions = ReadConditions(wrappedReader);
            }

            if (wrappedReader.IsStartElement(SamlConstants.ElementNames.Advice, SamlConstants.Namespace))
            {
                assertion.Advice = ReadAdvice(wrappedReader);
            }

            while (wrappedReader.IsStartElement())
            {
                assertion.Statements.Add(ReadStatement(wrappedReader));
            }

            if (assertion.Statements.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4078)));
            }

            wrappedReader.MoveToContent();
            wrappedReader.ReadEndElement();

            // Reading the end element will complete the signature; 
            // capture the signing creds
            assertion.SigningCredentials = wrappedReader.SigningCredentials;

            // Save the captured on-the-wire data, which can then be used
            // to re-emit this assertion, preserving the same signature.
            assertion.CaptureSourceData(wrappedReader);

            return assertion;
        }

        /// <summary>
        /// Serializes a given SamlAssertion to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to use for the serialization.</param>
        /// <param name="assertion">Assertion to be serialized into the XmlWriter.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'assertion' is null.</exception>
        protected virtual void WriteAssertion(XmlWriter writer, SamlAssertion assertion)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (assertion == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion");
            }

            SamlAssertion SamlAssertion = assertion as SamlAssertion;
            if (SamlAssertion != null)
            {
                if (SamlAssertion.CanWriteSourceData)
                {
                    SamlAssertion.WriteSourceData(writer);
                    return;
                }
            }

            if (assertion.SigningCredentials != null)
            {
                writer = new EnvelopedSignatureWriter(writer, assertion.SigningCredentials, assertion.AssertionId, new WrappedSerializer(this, assertion));
            }
            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Assertion, SamlConstants.Namespace);

            writer.WriteAttributeString(SamlConstants.AttributeNames.MajorVersion, null, Convert.ToString(SamlConstants.MajorVersionValue, CultureInfo.InvariantCulture));
            writer.WriteAttributeString(SamlConstants.AttributeNames.MinorVersion, null, Convert.ToString(SamlConstants.MinorVersionValue, CultureInfo.InvariantCulture));
            writer.WriteAttributeString(SamlConstants.AttributeNames.AssertionId, null, assertion.AssertionId);
            writer.WriteAttributeString(SamlConstants.AttributeNames.Issuer, null, assertion.Issuer);
            writer.WriteAttributeString(SamlConstants.AttributeNames.IssueInstant, null, assertion.IssueInstant.ToUniversalTime().ToString(DateTimeFormats.Generated, CultureInfo.InvariantCulture));

            // Write out conditions
            if (assertion.Conditions != null)
            {
                WriteConditions(writer, assertion.Conditions);
            }

            // Write out advice if there is one
            if (assertion.Advice != null)
            {
                WriteAdvice(writer, assertion.Advice);
            }

            // Write statements.
            for (int i = 0; i < assertion.Statements.Count; i++)
            {
                WriteStatement(writer, assertion.Statements[i]);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read saml:Conditions from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader to read the SAML conditions from.</param>
        /// <returns>SamlConditions</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The reader is not positioned at saml:Conditions element or contains 
        /// elements that are not recognized.</exception>
        protected virtual SamlConditions ReadConditions(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            SamlConditions conditions = new SamlConditions();
            string time = reader.GetAttribute(SamlConstants.AttributeNames.NotBefore, null);
            if (!string.IsNullOrEmpty(time))
            {
                conditions.NotBefore = DateTime.ParseExact(
                    time, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            time = reader.GetAttribute(SamlConstants.AttributeNames.NotOnOrAfter, null);
            if (!string.IsNullOrEmpty(time))
            {
                conditions.NotOnOrAfter = DateTime.ParseExact(
                    time, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            // Saml Conditions element is an optional element and all its child element
            // are optional as well. So we can have a empty <saml:Conditions /> element
            // in a valid Saml token.
            if (reader.IsEmptyElement)
            {
                // Just issue a read to read the Empty element.
                reader.MoveToContent();
                reader.Read();
                return conditions;
            }

            reader.ReadStartElement();

            while (reader.IsStartElement())
            {
                conditions.Conditions.Add(ReadCondition(reader));
            }

            reader.ReadEndElement();

            return conditions;
        }

        /// <summary>
        /// Serialize SamlConditions to the given XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to which the SamlConditions is serialized.</param>
        /// <param name="conditions">SamlConditions to be serialized.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'conditions' is null.</exception>
        protected virtual void WriteConditions(XmlWriter writer, SamlConditions conditions)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (conditions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("conditions");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Conditions, SamlConstants.Namespace);

            // SamlConditions when new'ed up will have the min and max values defined in WCF
            // which is different than our defaults. To maintin compatability with WCF behavior we will 
            // not write out SamlConditions NotBefore and NotOnOrAfter times which match the WCF
            // min and max default values as well.
            if (conditions.NotBefore != DateTimeUtil.GetMinValue(DateTimeKind.Utc) &&
                conditions.NotBefore != WCFMinValue)
            {
                writer.WriteAttributeString(
                    SamlConstants.AttributeNames.NotBefore,
                    null,
                    conditions.NotBefore.ToUniversalTime().ToString(DateTimeFormats.Generated, DateTimeFormatInfo.InvariantInfo));
            }

            if (conditions.NotOnOrAfter != DateTimeUtil.GetMaxValue(DateTimeKind.Utc) &&
                conditions.NotOnOrAfter != WCFMaxValue)
            {
                writer.WriteAttributeString(
                    SamlConstants.AttributeNames.NotOnOrAfter,
                    null,
                    conditions.NotOnOrAfter.ToUniversalTime().ToString(DateTimeFormats.Generated, DateTimeFormatInfo.InvariantInfo));
            }

            for (int i = 0; i < conditions.Conditions.Count; i++)
            {
                WriteCondition(writer, conditions.Conditions[i]);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read saml:AudienceRestrictionCondition or saml:DoNotCacheCondition from the given reader.
        /// </summary>
        /// <param name="reader">XmlReader to read the SamlCondition from.</param>
        /// <returns>SamlCondition</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">XmlReader is positioned at an unknown element.</exception>
        protected virtual SamlCondition ReadCondition(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (reader.IsStartElement(SamlConstants.ElementNames.AudienceRestrictionCondition, SamlConstants.Namespace))
            {
                return ReadAudienceRestrictionCondition(reader);
            }
            else if (reader.IsStartElement(SamlConstants.ElementNames.DoNotCacheCondition, SamlConstants.Namespace))
            {
                return ReadDoNotCacheCondition(reader);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4080, reader.LocalName, reader.NamespaceURI)));
            }
        }

        /// <summary>
        /// Serializes the given SamlCondition to the given XmlWriter. 
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the condition.</param>
        /// <param name="condition">SamlConditon to be serialized.</param>
        /// <exception cref="ArgumentNullException">The parameter 'condition' is null.</exception>
        /// <exception cref="SecurityTokenException">The given condition is unknown. By default only SamlAudienceRestrictionCondition
        /// and SamlDoNotCacheCondition are serialized.</exception>
        protected virtual void WriteCondition(XmlWriter writer, SamlCondition condition)
        {
            if (condition == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("condition");
            }

            SamlAudienceRestrictionCondition audienceRestrictionCondition = condition as SamlAudienceRestrictionCondition;
            if (audienceRestrictionCondition != null)
            {
                WriteAudienceRestrictionCondition(writer, audienceRestrictionCondition);
                return;
            }

            SamlDoNotCacheCondition doNotCacheCondition = condition as SamlDoNotCacheCondition;
            if (doNotCacheCondition != null)
            {
                WriteDoNotCacheCondition(writer, doNotCacheCondition);
                return;
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4081, condition.GetType())));
        }

        /// <summary>
        /// Read saml:AudienceRestrictionCondition from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a saml:AudienceRestrictionCondition.</param>
        /// <returns>SamlAudienceRestrictionCondition</returns>
        /// <exception cref="ArgumentNullException">The inpur parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at saml:AudienceRestrictionCondition.</exception>
        protected virtual SamlAudienceRestrictionCondition ReadAudienceRestrictionCondition(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.AudienceRestrictionCondition, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.AudienceRestrictionCondition, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            reader.ReadStartElement();

            SamlAudienceRestrictionCondition audienceRestrictionCondition = new SamlAudienceRestrictionCondition();
            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(SamlConstants.ElementNames.Audience, SamlConstants.Namespace))
                {
                    string audience = reader.ReadString();
                    if (string.IsNullOrEmpty(audience))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4083)));
                    }

                    audienceRestrictionCondition.Audiences.Add(new Uri(audience, UriKind.RelativeOrAbsolute));
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.Audience, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
                }
            }

            if (audienceRestrictionCondition.Audiences.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4084)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return audienceRestrictionCondition;
        }

        /// <summary>
        /// Serialize SamlAudienceRestrictionCondition to a XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlAudienceRestrictionCondition.</param>
        /// <param name="condition">SamlAudienceRestrictionCondition to serialize.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'condition' is null.</exception>
        protected virtual void WriteAudienceRestrictionCondition(XmlWriter writer, SamlAudienceRestrictionCondition condition)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (condition == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("condition");
            }

            // Schema requires at least one audience.
            if (condition.Audiences == null || condition.Audiences.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR.GetString(SR.ID4269)));
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AudienceRestrictionCondition, SamlConstants.Namespace);

            for (int i = 0; i < condition.Audiences.Count; i++)
            {
                // When writing out the audience uri we use the OriginalString property to preserve the value that was initially passed down during token creation as-is. 
                writer.WriteElementString(SamlConstants.ElementNames.Audience, SamlConstants.Namespace, condition.Audiences[i].OriginalString);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read saml:DoNotCacheCondition from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a saml:DoNotCacheCondition element.</param>
        /// <returns>SamlDoNotCacheCondition</returns>
        /// <exception cref="ArgumentNullException">The inpur parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at saml:DoNotCacheCondition.</exception>
        protected virtual SamlDoNotCacheCondition ReadDoNotCacheCondition(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.DoNotCacheCondition, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.DoNotCacheCondition, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            SamlDoNotCacheCondition doNotCacheCondition = new SamlDoNotCacheCondition();
            // saml:DoNotCacheCondition is a empty element. So just issue a read for
            // the empty element.
            if (reader.IsEmptyElement)
            {
                reader.MoveToContent();
                reader.Read();
                return doNotCacheCondition;
            }

            reader.MoveToContent();
            reader.ReadStartElement();
            reader.ReadEndElement();

            return doNotCacheCondition;
        }

        /// <summary>
        /// Serialize SamlDoNotCacheCondition to a XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlDoNotCacheCondition.</param>
        /// <param name="condition">SamlDoNotCacheCondition to serialize.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'condition' is null.</exception>
        protected virtual void WriteDoNotCacheCondition(XmlWriter writer, SamlDoNotCacheCondition condition)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (condition == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("condition");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.DoNotCacheCondition, SamlConstants.Namespace);
            writer.WriteEndElement();
        }

        /// <summary>
        /// Read a SamlStatement from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a SamlStatement.</param>
        /// <returns>SamlStatement</returns>
        /// <exception cref="ArgumentNullException">The inpur parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at recognized SamlStatement. By default,
        /// only saml:AuthenticationStatement, saml:AttributeStatement and saml:AuthorizationDecisionStatement.</exception>
        protected virtual SamlStatement ReadStatement(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (reader.IsStartElement(SamlConstants.ElementNames.AuthenticationStatement, SamlConstants.Namespace))
            {
                return ReadAuthenticationStatement(reader);
            }
            else if (reader.IsStartElement(SamlConstants.ElementNames.AttributeStatement, SamlConstants.Namespace))
            {
                return ReadAttributeStatement(reader);
            }
            else if (reader.IsStartElement(SamlConstants.ElementNames.AuthorizationDecisionStatement, SamlConstants.Namespace))
            {
                return ReadAuthorizationDecisionStatement(reader);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4085, reader.LocalName, reader.NamespaceURI)));
            }

        }

        /// <summary>
        /// Serialize the SamlStatement to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlStatement.</param>
        /// <param name="statement">The SamlStatement to serialize.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'statement' is null.</exception>
        /// <exception cref="SecurityTokenException">The SamlStatement is not recognized. Only SamlAuthenticationStatement,
        /// SamlAuthorizationStatement and SamlAttributeStatement are recognized.</exception>
        protected virtual void WriteStatement(XmlWriter writer, SamlStatement statement)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (statement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statement");
            }

            SamlAuthenticationStatement authnStatement = statement as SamlAuthenticationStatement;
            if (authnStatement != null)
            {
                WriteAuthenticationStatement(writer, authnStatement);
                return;
            }

            SamlAuthorizationDecisionStatement authzStatement = statement as SamlAuthorizationDecisionStatement;
            if (authzStatement != null)
            {
                WriteAuthorizationDecisionStatement(writer, authzStatement);
                return;
            }

            SamlAttributeStatement attributeStatement = statement as SamlAttributeStatement;
            if (attributeStatement != null)
            {
                WriteAttributeStatement(writer, attributeStatement);
                return;
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4086, statement.GetType())));
        }

        /// <summary>
        /// Read the SamlSubject from the XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader to read the SamlSubject from.</param>
        /// <returns>SamlSubject</returns>
        /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception>
        /// <exception cref="XmlException">The reader is not positioned at a SamlSubject.</exception>
        protected virtual SamlSubject ReadSubject(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.Subject, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.Subject, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            SamlSubject subject = new SamlSubject();

            reader.ReadStartElement(SamlConstants.ElementNames.Subject, SamlConstants.Namespace);
            if (reader.IsStartElement(SamlConstants.ElementNames.NameIdentifier, SamlConstants.Namespace))
            {
                subject.NameFormat = reader.GetAttribute(SamlConstants.AttributeNames.NameIdentifierFormat, null);
                subject.NameQualifier = reader.GetAttribute(SamlConstants.AttributeNames.NameIdentifierNameQualifier, null);

                reader.MoveToContent();
                subject.Name = reader.ReadElementString();

                if (string.IsNullOrEmpty(subject.Name))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4087)));
                }
            }

            if (reader.IsStartElement(SamlConstants.ElementNames.SubjectConfirmation, SamlConstants.Namespace))
            {
                reader.ReadStartElement();

                while (reader.IsStartElement(SamlConstants.ElementNames.SubjectConfirmationMethod, SamlConstants.Namespace))
                {
                    string method = reader.ReadElementString();
                    if (string.IsNullOrEmpty(method))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4088)));
                    }

                    subject.ConfirmationMethods.Add(method);
                }

                if (subject.ConfirmationMethods.Count == 0)
                {
                    // A SubjectConfirmaton clause should specify at least one 
                    // ConfirmationMethod.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4088)));
                }

                if (reader.IsStartElement(SamlConstants.ElementNames.SubjectConfirmationData, SamlConstants.Namespace))
                {
                    // An Authentication protocol specified in the confirmation method might need this
                    // data. Just store this content value as string.
                    subject.SubjectConfirmationData = reader.ReadElementString();
                }

                if (reader.IsStartElement(XmlSignatureConstants.Elements.KeyInfo, XmlSignatureConstants.Namespace))
                {
                    subject.KeyIdentifier = ReadSubjectKeyInfo(reader);
                    SecurityKey key = ResolveSubjectKeyIdentifier(subject.KeyIdentifier);
                    if (key != null)
                    {
                        subject.Crypto = key;
                    }
                    else
                    {
                        subject.Crypto = new SecurityKeyElement(subject.KeyIdentifier, this.Configuration.ServiceTokenResolver);
                    }
                }


                if ((subject.ConfirmationMethods.Count == 0) && (string.IsNullOrEmpty(subject.Name)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4089)));
                }

                reader.MoveToContent();
                reader.ReadEndElement();
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return subject;
        }

        /// <summary>
        /// Serialize the given SamlSubject into an XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter into which the SamlSubject is serialized.</param>
        /// <param name="subject">SamlSubject to be serialized.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'subject' or 'writer' is null.</exception>
        protected virtual void WriteSubject(XmlWriter writer, SamlSubject subject)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (subject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subject");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Subject, SamlConstants.Namespace);
            if (!string.IsNullOrEmpty(subject.Name))
            {
                writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.NameIdentifier, SamlConstants.Namespace);
                if (!string.IsNullOrEmpty(subject.NameFormat))
                {
                    writer.WriteAttributeString(SamlConstants.AttributeNames.NameIdentifierFormat, null, subject.NameFormat);
                }
                if (subject.NameQualifier != null)
                {
                    writer.WriteAttributeString(SamlConstants.AttributeNames.NameIdentifierNameQualifier, null, subject.NameQualifier);
                }
                writer.WriteString(subject.Name);
                writer.WriteEndElement();
            }

            if (subject.ConfirmationMethods.Count > 0)
            {
                writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.SubjectConfirmation, SamlConstants.Namespace);

                foreach (string method in subject.ConfirmationMethods)
                {
                    writer.WriteElementString(SamlConstants.ElementNames.SubjectConfirmationMethod, SamlConstants.Namespace, method);
                }

                if (!string.IsNullOrEmpty(subject.SubjectConfirmationData))
                {
                    writer.WriteElementString(SamlConstants.ElementNames.SubjectConfirmationData, SamlConstants.Namespace, subject.SubjectConfirmationData);
                }

                if (subject.KeyIdentifier != null)
                {
                    WriteSubjectKeyInfo(writer, subject.KeyIdentifier);
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read the SamlSubject KeyIdentifier from a XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at the SamlSubject KeyIdentifier.</param>
        /// <returns>SamlSubject Key as a SecurityKeyIdentifier.</returns>
        /// <exception cref="ArgumentNullException">Input parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">XmlReader is not positioned at a valid SecurityKeyIdentifier.</exception>
        protected virtual SecurityKeyIdentifier ReadSubjectKeyInfo(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (KeyInfoSerializer.CanReadKeyIdentifier(reader))
            {
                return KeyInfoSerializer.ReadKeyIdentifier(reader);
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4090)));
        }

        /// <summary>
        /// Write the SamlSubject SecurityKeyIdentifier to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to write the SecurityKeyIdentifier.</param>
        /// <param name="subjectSki">SecurityKeyIdentifier to serialize.</param>
        /// <exception cref="ArgumentNullException">The inpur parameter 'writer' or 'subjectSki' is null.</exception>
        protected virtual void WriteSubjectKeyInfo(XmlWriter writer, SecurityKeyIdentifier subjectSki)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (subjectSki == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subjectSki");
            }

            if (KeyInfoSerializer.CanWriteKeyIdentifier(subjectSki))
            {
                KeyInfoSerializer.WriteKeyIdentifier(writer, subjectSki);
                return;
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("subjectSki", SR.GetString(SR.ID4091, subjectSki.GetType()));
        }

        /// <summary>
        /// Read saml:AttributeStatement from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a saml:AttributeStatement element.</param>
        /// <returns>SamlAttributeStatement</returns>
        /// <exception cref="ArgumentNullException">Input parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">XmlReader is not positioned at a saml:AttributeStatement element or
        /// the AttributeStatement contains unrecognized elements.</exception>
        protected virtual SamlAttributeStatement ReadAttributeStatement(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.AttributeStatement, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.AttributeStatement, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            reader.ReadStartElement();

            SamlAttributeStatement attributeStatement = new SamlAttributeStatement();
            if (reader.IsStartElement(SamlConstants.ElementNames.Subject, SamlConstants.Namespace))
            {
                attributeStatement.SamlSubject = ReadSubject(reader);
            }
            else
            {
                // SAML Subject is a required Attribute Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4092)));
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(SamlConstants.ElementNames.Attribute, SamlConstants.Namespace))
                {
                    // SAML Attribute is a extensibility point. So ask the SAML serializer 
                    // to load this part.
                    attributeStatement.Attributes.Add(ReadAttribute(reader));
                }
                else
                {
                    break;
                }
            }

            if (attributeStatement.Attributes.Count == 0)
            {
                // Each Attribute statement should have at least one attribute.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4093)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return attributeStatement;
        }

        /// <summary>
        /// Serialize a SamlAttributeStatement.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the given statement.</param>
        /// <param name="statement">SamlAttributeStatement to write to the XmlWriter.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'statement' is null.</exception>
        protected virtual void WriteAttributeStatement(XmlWriter writer, SamlAttributeStatement statement)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (statement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statement");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AttributeStatement, SamlConstants.Namespace);

            WriteSubject(writer, statement.SamlSubject);

            for (int i = 0; i < statement.Attributes.Count; i++)
            {
                WriteAttribute(writer, statement.Attributes[i]);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read an saml:Attribute element.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a saml:Attribute element.</param>
        /// <returns>SamlAttribute</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned on a valid saml:Attribute element.</exception>
        protected virtual SamlAttribute ReadAttribute(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            SamlAttribute attribute = new SamlAttribute();

            attribute.Name = reader.GetAttribute(SamlConstants.AttributeNames.AttributeName, null);
            if (string.IsNullOrEmpty(attribute.Name))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4094)));
            }

            attribute.Namespace = reader.GetAttribute(SamlConstants.AttributeNames.AttributeNamespace, null);
            if (string.IsNullOrEmpty(attribute.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4095)));
            }

            //
            // OriginalIssuer is an optional attribute.
            // We are lax on read here, and will accept the following namespaces for original issuer, in order:
            // http://schemas.xmlsoap.org/ws/2009/09/identity/claims
            // http://schemas.microsoft.com/ws/2008/06/identity
            //
            string originalIssuer = reader.GetAttribute(SamlConstants.AttributeNames.OriginalIssuer, ClaimType2009Namespace);

            if (originalIssuer == null)
            {
                originalIssuer = reader.GetAttribute(SamlConstants.AttributeNames.OriginalIssuer, ProductConstants.NamespaceUri);
            }

            if (originalIssuer == String.Empty)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4252)));
            }
            attribute.OriginalIssuer = originalIssuer;

            reader.MoveToContent();
            reader.Read();
            while (reader.IsStartElement(SamlConstants.ElementNames.AttributeValue, SamlConstants.Namespace))
            {
                // FIP 9570 - ENTERPRISE SCENARIO: Saml11SecurityTokenHandler.ReadAttribute is not checking the AttributeValue XSI type correctly.
                // Lax on receive. If we dont find the AttributeValueXsiType in the format we are looking for in the xml, we default to string.
                // Read the xsi:type. We are expecting a value of the form "some-non-empty-string" or "some-non-empty-local-prefix:some-non-empty-string".
                // ":some-non-empty-string" and "some-non-empty-string:" are edge-cases where defaulting to string is reasonable.
                string attributeValueXsiTypePrefix = null;
                string attributeValueXsiTypeSuffix = null;
                string attributeValueXsiTypeSuffixWithLocalPrefix = reader.GetAttribute("type", XmlSchema.InstanceNamespace);
                if (!string.IsNullOrEmpty(attributeValueXsiTypeSuffixWithLocalPrefix))
                {
                    if (attributeValueXsiTypeSuffixWithLocalPrefix.IndexOf(":", StringComparison.Ordinal) == -1) // "some-non-empty-string" case
                    {
                        attributeValueXsiTypePrefix = reader.LookupNamespace(String.Empty);
                        attributeValueXsiTypeSuffix = attributeValueXsiTypeSuffixWithLocalPrefix;
                    }
                    else if (attributeValueXsiTypeSuffixWithLocalPrefix.IndexOf(":", StringComparison.Ordinal) > 0 &&
                              attributeValueXsiTypeSuffixWithLocalPrefix.IndexOf(":", StringComparison.Ordinal) < attributeValueXsiTypeSuffixWithLocalPrefix.Length - 1) // "some-non-empty-local-prefix:some-non-empty-string" case
                    {
                        string localPrefix = attributeValueXsiTypeSuffixWithLocalPrefix.Substring(0, attributeValueXsiTypeSuffixWithLocalPrefix.IndexOf(":", StringComparison.Ordinal));
                        attributeValueXsiTypePrefix = reader.LookupNamespace(localPrefix);
                        // For attributeValueXsiTypeSuffix, we want the portion after the local prefix in "some-non-empty-local-prefix:some-non-empty-string"
                        attributeValueXsiTypeSuffix = attributeValueXsiTypeSuffixWithLocalPrefix.Substring(attributeValueXsiTypeSuffixWithLocalPrefix.IndexOf(":", StringComparison.Ordinal) + 1);
                    }
                }
                if (attributeValueXsiTypePrefix != null && attributeValueXsiTypeSuffix != null)
                {
                    attribute.AttributeValueXsiType = String.Concat(attributeValueXsiTypePrefix, "#", attributeValueXsiTypeSuffix);
                }

                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    attribute.AttributeValues.Add(string.Empty);
                }
                else
                {
                    attribute.AttributeValues.Add(ReadAttributeValue(reader, attribute));
                }
            }

            if (attribute.AttributeValues.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4212)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return attribute;
        }


        /// <summary>
        /// Reads an attribute value.
        /// </summary>
        /// <param name="reader">XmlReader to read from.</param>
        /// <param name="attribute">The current attribute that is being read.</param>
        /// <returns>The attribute value as a string.</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        protected virtual string ReadAttributeValue(XmlReader reader, SamlAttribute attribute)
        {
            // This code was designed realizing that the writter of the xml controls how our
            // reader will report the NodeType. A completely differnet system (IBM, etc) could write the values. 
            // Considering NodeType is important, because we need to read the entire value, end element and not loose anything significant.
            // 
            // Couple of cases to help understand the design choices.
            //
            // 1. 
            // "<MyElement xmlns=""urn:mynamespace""><another>complex</another></MyElement><sibling>value</sibling>"
            // Could result in the our reader reporting the NodeType as Text OR Element, depending if '<' was entitized to '&lt;'
            //
            // 2. 
            // " <MyElement xmlns=""urn:mynamespace""><another>complex</another></MyElement><sibling>value</sibling>"
            // Could result in the our reader reporting the NodeType as Text OR Whitespace.  Post Whitespace processing, the NodeType could be 
            // reported as Text or Element, depending if '<' was entitized to '&lt;'
            //
            // 3. 
            // "/r/n/t   "
            // Could result in the our reader reporting the NodeType as whitespace.
            //
            // Since an AttributeValue with ONLY Whitespace and a complex Element proceeded by whitespace are reported as the same NodeType (2. and 3.)
            // the whitespace is remembered and discarded if an found is found, otherwise it becomes the value. This is to help users who accidently put a space when adding claims in ADFS
            // If we just skipped the Whitespace, then an AttributeValue that started with Whitespace would loose that part and claims generated from the AttributeValue
            // would be missing that part.
            // 

            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            string result = String.Empty;
            string whiteSpace = String.Empty;

            reader.ReadStartElement(Saml2Constants.Elements.AttributeValue, SamlConstants.Namespace);

            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                whiteSpace += reader.Value;
                reader.Read();
            }

            reader.MoveToContent();
            if (reader.NodeType == XmlNodeType.Element)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    result += reader.ReadOuterXml();
                    reader.MoveToContent();
                }
            }
            else
            {
                result = whiteSpace;
                result += reader.ReadContentAsString();
            }

            reader.ReadEndElement();
            return result;
        }

        /// <summary>
        /// Serializes a given SamlAttribute.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlAttribute.</param>
        /// <param name="attribute">SamlAttribute to be serialized.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'attribute' is null.</exception>
        protected virtual void WriteAttribute(XmlWriter writer, SamlAttribute attribute)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (attribute == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attribute");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Attribute, SamlConstants.Namespace);

            writer.WriteAttributeString(SamlConstants.AttributeNames.AttributeName, null, attribute.Name);
            writer.WriteAttributeString(SamlConstants.AttributeNames.AttributeNamespace, null, attribute.Namespace);

            SamlAttribute SamlAttribute = attribute as SamlAttribute;
            if ((SamlAttribute != null) && (SamlAttribute.OriginalIssuer != null))
            {
                writer.WriteAttributeString(SamlConstants.AttributeNames.OriginalIssuer, ClaimType2009Namespace, SamlAttribute.OriginalIssuer);
            }

            string xsiTypePrefix = null;
            string xsiTypeSuffix = null;
            if (SamlAttribute != null && !StringComparer.Ordinal.Equals(SamlAttribute.AttributeValueXsiType, ClaimValueTypes.String))
            {
                // ClaimValueTypes are URIs of the form prefix#suffix, while xsi:type should be a QName.
                // Hence, the tokens-to-claims spec requires that ClaimValueTypes be serialized as xmlns:tn="prefix" xsi:type="tn:suffix"
                int indexOfHash = SamlAttribute.AttributeValueXsiType.IndexOf('#');
                xsiTypePrefix = SamlAttribute.AttributeValueXsiType.Substring(0, indexOfHash);
                xsiTypeSuffix = SamlAttribute.AttributeValueXsiType.Substring(indexOfHash + 1);
            }

            for (int i = 0; i < attribute.AttributeValues.Count; i++)
            {
                if (attribute.AttributeValues[i] == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4096)));
                }

                writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AttributeValue, SamlConstants.Namespace);
                if ((xsiTypePrefix != null) && (xsiTypeSuffix != null))
                {
                    writer.WriteAttributeString("xmlns", ProductConstants.ClaimValueTypeSerializationPrefix, null, xsiTypePrefix);
                    writer.WriteAttributeString("type", XmlSchema.InstanceNamespace, String.Concat(ProductConstants.ClaimValueTypeSerializationPrefixWithColon, xsiTypeSuffix));
                }
                WriteAttributeValue(writer, attribute.AttributeValues[i], attribute);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Writes the saml:Attribute value.
        /// </summary>
        /// <param name="writer">XmlWriter to which to write.</param>
        /// <param name="value">Attribute value to be written.</param>
        /// <param name="attribute">The SAML attribute whose value is being written.</param>
        /// <remarks>By default the method writes the value as a string.</remarks>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' is null.</exception>
        protected virtual void WriteAttributeValue(XmlWriter writer, string value, SamlAttribute attribute)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            writer.WriteString(value);
        }

        /// <summary>
        /// Read the saml:AuthenticationStatement.
        /// </summary>
        /// <param name="reader">XmlReader positioned at a saml:AuthenticationStatement.</param>
        /// <returns>SamlAuthenticationStatement</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned on a saml:AuthenticationStatement
        /// or the statement contains a unknown child element.</exception>
        protected virtual SamlAuthenticationStatement ReadAuthenticationStatement(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.AuthenticationStatement, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.AuthenticationStatement, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            SamlAuthenticationStatement authnStatement = new SamlAuthenticationStatement();
            string authInstance = reader.GetAttribute(SamlConstants.AttributeNames.AuthenticationInstant, null);
            if (string.IsNullOrEmpty(authInstance))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4097)));
            }
            authnStatement.AuthenticationInstant = DateTime.ParseExact(
                authInstance, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();

            authnStatement.AuthenticationMethod = reader.GetAttribute(SamlConstants.AttributeNames.AuthenticationMethod, null);
            if (string.IsNullOrEmpty(authnStatement.AuthenticationMethod))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4098)));
            }

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(SamlConstants.ElementNames.Subject, SamlConstants.Namespace))
            {
                authnStatement.SamlSubject = ReadSubject(reader);
            }
            else
            {
                // Subject is a required element for a Authentication Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4099)));
            }

            if (reader.IsStartElement(SamlConstants.ElementNames.SubjectLocality, SamlConstants.Namespace))
            {
                authnStatement.DnsAddress = reader.GetAttribute(SamlConstants.AttributeNames.SubjectLocalityDNSAddress, null);
                authnStatement.IPAddress = reader.GetAttribute(SamlConstants.AttributeNames.SubjectLocalityIPAddress, null);

                if (reader.IsEmptyElement)
                {
                    reader.MoveToContent();
                    reader.Read();
                }
                else
                {
                    reader.MoveToContent();
                    reader.Read();
                    reader.ReadEndElement();
                }
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(SamlConstants.ElementNames.AuthorityBinding, SamlConstants.Namespace))
                {
                    authnStatement.AuthorityBindings.Add(ReadAuthorityBinding(reader));
                }
                else
                {
                    // We do not understand this element.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.AuthorityBinding, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
                }
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return authnStatement;
        }

        /// <summary>
        /// Serializes a given SamlAuthenticationStatement.
        /// </summary>
        /// <param name="writer">XmlWriter to which SamlAuthenticationStatement is serialized.</param>
        /// <param name="statement">SamlAuthenticationStatement to be serialized.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'statement' is null.</exception>
        protected virtual void WriteAuthenticationStatement(XmlWriter writer, SamlAuthenticationStatement statement)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (statement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statement");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AuthenticationStatement, SamlConstants.Namespace);

            writer.WriteAttributeString(SamlConstants.AttributeNames.AuthenticationMethod, null, statement.AuthenticationMethod);

            writer.WriteAttributeString(SamlConstants.AttributeNames.AuthenticationInstant, null,
                             XmlConvert.ToString(statement.AuthenticationInstant.ToUniversalTime(), DateTimeFormats.Generated));


            WriteSubject(writer, statement.SamlSubject);

            if ((statement.IPAddress != null) || (statement.DnsAddress != null))
            {
                writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.SubjectLocality, SamlConstants.Namespace);

                if (statement.IPAddress != null)
                {
                    writer.WriteAttributeString(SamlConstants.AttributeNames.SubjectLocalityIPAddress, null, statement.IPAddress);
                }

                if (statement.DnsAddress != null)
                {
                    writer.WriteAttributeString(SamlConstants.AttributeNames.SubjectLocalityDNSAddress, null, statement.DnsAddress);
                }

                writer.WriteEndElement();
            }

            for (int i = 0; i < statement.AuthorityBindings.Count; i++)
            {
                WriteAuthorityBinding(writer, statement.AuthorityBindings[i]);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read the saml:AuthorityBinding element.
        /// </summary>
        /// <param name="reader">XmlReader positioned at the saml:AuthorityBinding element.</param>
        /// <returns>SamlAuthorityBinding</returns>
        /// <exception cref="ArgumentNullException">The inpur parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">XmlReader is not positioned at a saml:AuthorityBinding element or
        /// contains a unrecognized or invalid child element.</exception>
        protected virtual SamlAuthorityBinding ReadAuthorityBinding(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            SamlAuthorityBinding authorityBinding = new SamlAuthorityBinding();
            string authKind = reader.GetAttribute(SamlConstants.AttributeNames.AuthorityKind, null);
            if (string.IsNullOrEmpty(authKind))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4200)));
            }

            string[] authKindParts = authKind.Split(':');
            if (authKindParts.Length > 2)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4201, authKind)));
            }

            string localName;
            string prefix;
            string nameSpace;
            if (authKindParts.Length == 2)
            {
                prefix = authKindParts[0];
                localName = authKindParts[1];
            }
            else
            {
                prefix = String.Empty;
                localName = authKindParts[0];
            }

            nameSpace = reader.LookupNamespace(prefix);

            authorityBinding.AuthorityKind = new XmlQualifiedName(localName, nameSpace);

            authorityBinding.Binding = reader.GetAttribute(SamlConstants.AttributeNames.Binding, null);
            if (string.IsNullOrEmpty(authorityBinding.Binding))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4202)));
            }

            authorityBinding.Location = reader.GetAttribute(SamlConstants.AttributeNames.Location, null);
            if (string.IsNullOrEmpty(authorityBinding.Location))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4203)));
            }

            if (reader.IsEmptyElement)
            {
                reader.MoveToContent();
                reader.Read();
            }
            else
            {
                reader.MoveToContent();
                reader.Read();
                reader.ReadEndElement();
            }

            return authorityBinding;
        }

        /// <summary>
        /// Serialize a SamlAuthorityBinding.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlAuthorityBinding</param>
        /// <param name="authorityBinding">SamlAuthoriyBinding to be serialized.</param>
        protected virtual void WriteAuthorityBinding(XmlWriter writer, SamlAuthorityBinding authorityBinding)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (authorityBinding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statement");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AuthorityBinding, SamlConstants.Namespace);

            string prefix = null;
            if (!string.IsNullOrEmpty(authorityBinding.AuthorityKind.Namespace))
            {
                writer.WriteAttributeString(String.Empty, SamlConstants.AttributeNames.NamespaceAttributePrefix, null, authorityBinding.AuthorityKind.Namespace);
                prefix = writer.LookupPrefix(authorityBinding.AuthorityKind.Namespace);
            }

            writer.WriteStartAttribute(SamlConstants.AttributeNames.AuthorityKind, null);
            if (string.IsNullOrEmpty(prefix))
            {
                writer.WriteString(authorityBinding.AuthorityKind.Name);
            }
            else
            {
                writer.WriteString(prefix + ":" + authorityBinding.AuthorityKind.Name);
            }
            writer.WriteEndAttribute();

            writer.WriteAttributeString(SamlConstants.AttributeNames.Location, null, authorityBinding.Location);

            writer.WriteAttributeString(SamlConstants.AttributeNames.Binding, null, authorityBinding.Binding);

            writer.WriteEndElement();
        }

        /// <summary>
        /// Gets a boolean indicating if the SecurityTokenHandler can Serialize Tokens. Return true by default.
        /// </summary>
        public override bool CanWriteToken
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Serializes the given SecurityToken to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter into which the token is serialized.</param>
        /// <param name="token">SecurityToken to be serialized.</param>
        /// <exception cref="ArgumentNullException">Input parameter 'writer' or 'token' is null.</exception>
        /// <exception cref="SecurityTokenException">The given 'token' is not a SamlSecurityToken.</exception>
        public override void WriteToken(XmlWriter writer, SecurityToken token)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SamlSecurityToken samlSecurityToken = token as SamlSecurityToken;
            if (samlSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4217, token.GetType(), typeof(SamlSecurityToken))));
            }

            WriteAssertion(writer, samlSecurityToken.Assertion);
        }

        /// <summary>
        /// Read the saml:AuthorizationDecisionStatement element.
        /// </summary>
        /// <param name="reader">XmlReader position at saml:AuthorizationDecisionStatement.</param>
        /// <returns>SamlAuthorizationDecisionStatement</returns>
        /// <exception cref="ArgumentNullException">The inpur parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at a saml:AuthorizationDecisionStatement or
        /// the statement contains child elments that are unknown or invalid.</exception>
        protected virtual
        SamlAuthorizationDecisionStatement ReadAuthorizationDecisionStatement(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.AuthorizationDecisionStatement, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.AuthorizationDecisionStatement, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            SamlAuthorizationDecisionStatement authzStatement = new SamlAuthorizationDecisionStatement();
            authzStatement.Resource = reader.GetAttribute(SamlConstants.AttributeNames.Resource, null);
            if (string.IsNullOrEmpty(authzStatement.Resource))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4205)));
            }

            string decisionString = reader.GetAttribute(SamlConstants.AttributeNames.Decision, null);
            if (string.IsNullOrEmpty(decisionString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4204)));
            }

            if (decisionString.Equals(SamlAccessDecision.Deny.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                authzStatement.AccessDecision = SamlAccessDecision.Deny;
            }
            else if (decisionString.Equals(SamlAccessDecision.Permit.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                authzStatement.AccessDecision = SamlAccessDecision.Permit;
            }
            else
            {
                authzStatement.AccessDecision = SamlAccessDecision.Indeterminate;
            }

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(SamlConstants.ElementNames.Subject, SamlConstants.Namespace))
            {
                authzStatement.SamlSubject = ReadSubject(reader);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4206)));
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(SamlConstants.ElementNames.Action, SamlConstants.Namespace))
                {
                    authzStatement.SamlActions.Add(ReadAction(reader));
                }
                else if (reader.IsStartElement(SamlConstants.ElementNames.Evidence, SamlConstants.Namespace))
                {
                    if (authzStatement.Evidence != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4207)));
                    }

                    authzStatement.Evidence = ReadEvidence(reader);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4208, reader.LocalName, reader.NamespaceURI)));
                }
            }

            if (authzStatement.SamlActions.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4209)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return authzStatement;
        }

        /// <summary>
        /// Serialize a SamlAuthorizationDecisionStatement.
        /// </summary>
        /// <param name="writer">XmlWriter to which the SamlAuthorizationStatement is serialized.</param>
        /// <param name="statement">SamlAuthorizationDecisionStatement to serialize.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'statement' is null.</exception>
        protected virtual void WriteAuthorizationDecisionStatement(XmlWriter writer, SamlAuthorizationDecisionStatement statement)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (statement == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statement");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.AuthorizationDecisionStatement, SamlConstants.Namespace);

            writer.WriteAttributeString(SamlConstants.AttributeNames.Decision, null, statement.AccessDecision.ToString());

            writer.WriteAttributeString(SamlConstants.AttributeNames.Resource, null, statement.Resource);

            WriteSubject(writer, statement.SamlSubject);

            foreach (SamlAction action in statement.SamlActions)
            {
                WriteAction(writer, action);
            }

            if (statement.Evidence != null)
            {
                WriteEvidence(writer, statement.Evidence);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Read the saml:Evidence element.
        /// </summary>
        /// <param name="reader">XmlReader positioned at saml:Evidence element.</param>
        /// <returns>SamlEvidence</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The XmlReader is not positioned at a saml:Evidence element or 
        /// the element contains unrecognized or invalid child elements.</exception>
        protected virtual SamlEvidence ReadEvidence(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (!reader.IsStartElement(SamlConstants.ElementNames.Evidence, SamlConstants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4082, SamlConstants.ElementNames.Evidence, SamlConstants.Namespace, reader.LocalName, reader.NamespaceURI)));
            }

            SamlEvidence evidence = new SamlEvidence();
            reader.ReadStartElement();

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(SamlConstants.ElementNames.AssertionIdReference, SamlConstants.Namespace))
                {
                    evidence.AssertionIdReferences.Add(reader.ReadElementString());
                }
                else if (reader.IsStartElement(SamlConstants.ElementNames.Assertion, SamlConstants.Namespace))
                {
                    evidence.Assertions.Add(ReadAssertion(reader));
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4210, reader.LocalName, reader.NamespaceURI)));
                }
            }

            if ((evidence.AssertionIdReferences.Count == 0) && (evidence.Assertions.Count == 0))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4211)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();

            return evidence;
        }

        /// <summary>
        /// Serializes a given SamlEvidence.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SamlEvidence.</param>
        /// <param name="evidence">SamlEvidence to be serialized.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'evidence' is null.</exception>
        protected virtual void WriteEvidence(XmlWriter writer, SamlEvidence evidence)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (evidence == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("evidence");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Evidence, SamlConstants.Namespace);

            for (int i = 0; i < evidence.AssertionIdReferences.Count; i++)
            {
                writer.WriteElementString(SamlConstants.Prefix, SamlConstants.ElementNames.AssertionIdReference, SamlConstants.Namespace, evidence.AssertionIdReferences[i]);
            }

            for (int i = 0; i < evidence.Assertions.Count; i++)
            {
                WriteAssertion(writer, evidence.Assertions[i]);
            }

            writer.WriteEndElement();
        }

        /// <summary>
        /// Resolves the SecurityKeyIdentifier specified in a saml:Subject element. 
        /// </summary>
        /// <param name="subjectKeyIdentifier">SecurityKeyIdentifier to resolve into a key.</param>
        /// <returns>SecurityKey</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'subjectKeyIdentifier' is null.</exception>
        protected virtual SecurityKey ResolveSubjectKeyIdentifier(SecurityKeyIdentifier subjectKeyIdentifier)
        {
            if (subjectKeyIdentifier == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("subjectKeyIdentifier");
            }

            if (this.Configuration == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274));
            }

            if (this.Configuration.ServiceTokenResolver == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4276));
            }

            SecurityKey key = null;
            foreach (SecurityKeyIdentifierClause clause in subjectKeyIdentifier)
            {
                if (this.Configuration.ServiceTokenResolver.TryResolveSecurityKey(clause, out key))
                {
                    return key;
                }
            }

            if (subjectKeyIdentifier.CanCreateKey)
            {
                return subjectKeyIdentifier.CreateKey();
            }

            return null;
        }

        /// <summary>
        /// Resolves the Signing Key Identifier to a SecurityToken.
        /// </summary>
        /// <param name="assertion">The Assertion for which the Issuer token is to be resolved.</param>
        /// <param name="issuerResolver">The current SecurityTokenResolver associated with this handler.</param>
        /// <returns>Instance of SecurityToken</returns>
        /// <exception cref="ArgumentNullException">Input parameter 'assertion' is null.</exception>
        /// <exception cref="ArgumentNullException">Input parameter 'issuerResolver' is null.</exception>/// 
        /// <exception cref="SecurityTokenException">Unable to resolve token.</exception>
        protected virtual SecurityToken ResolveIssuerToken(SamlAssertion assertion, SecurityTokenResolver issuerResolver)
        {
            if (null == assertion)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion");
            }

            if (null == issuerResolver)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuerResolver");
            }

            SecurityToken token;
            if (TryResolveIssuerToken(assertion, issuerResolver, out token))
            {
                return token;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4220)));
            }
        }

        /// <summary>
        /// Resolves the Signing Key Identifier to a SecurityToken.
        /// </summary>
        /// <param name="assertion">The Assertion for which the Issuer token is to be resolved.</param>
        /// <param name="issuerResolver">The current SecurityTokenResolver associated with this handler.</param>
        /// <param name="token">Resolved token.</param>
        /// <returns>True if token is resolved.</returns>
        /// <exception cref="ArgumentNullException">Input parameter 'assertion' is null.</exception>
        protected virtual bool TryResolveIssuerToken(SamlAssertion assertion, SecurityTokenResolver issuerResolver, out SecurityToken token)
        {
            if (null == assertion)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion");
            }

            if (assertion.SigningCredentials != null
                && assertion.SigningCredentials.SigningKeyIdentifier != null
                && issuerResolver != null)
            {
                SecurityKeyIdentifier keyIdentifier = assertion.SigningCredentials.SigningKeyIdentifier;
                return issuerResolver.TryResolveToken(keyIdentifier, out token);
            }
            else
            {
                token = null;
                return false;
            }
        }

        /// <summary>
        /// Reads the ds:KeyInfo element inside the Saml Signature.
        /// </summary>
        /// <param name="reader">An XmlReader that can be positioned at a ds:KeyInfo element.</param>
        /// <param name="assertion">The assertion that is having the signature checked.</param>
        /// <returns>The <see cref="SecurityKeyIdentifier"/> that defines the key to use to check the signature.</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        /// <exception cref="InvalidOperationException">Unable to read the KeyIdentifier from the XmlReader.</exception>
        /// <remarks>If the reader is not positioned at a ds:KeyInfo element, the <see cref="SecurityKeyIdentifier"/> returned will
        /// contain a single <see cref="SecurityKeyIdentifierClause"/> of type <see cref="EmptySecurityKeyIdentifierClause"/></remarks>
        protected virtual SecurityKeyIdentifier ReadSigningKeyInfo(XmlReader reader, SamlAssertion assertion)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            SecurityKeyIdentifier ski;

            if (KeyInfoSerializer.CanReadKeyIdentifier(reader))
            {
                ski = KeyInfoSerializer.ReadKeyIdentifier(reader);
            }
            else
            {
                KeyInfo keyInfo = new KeyInfo(KeyInfoSerializer);
                keyInfo.ReadXml(XmlDictionaryReader.CreateDictionaryReader(reader));
                ski = keyInfo.KeyIdentifier;
            }

            // no key info
            if (ski.Count == 0)
            {
                return new SecurityKeyIdentifier(new SamlSecurityKeyIdentifierClause(assertion));
            }

            return ski;
        }

        /// <summary>
        /// Serializes the Signing SecurityKeyIdentifier.
        /// </summary>
        /// <param name="writer">XmlWriter to serialize the SecurityKeyIdentifier.</param>
        /// <param name="signingKeyIdentifier">Signing SecurityKeyIdentifier.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'signingKeyIdentifier' is null.</exception>
        protected virtual void WriteSigningKeyInfo(XmlWriter writer, SecurityKeyIdentifier signingKeyIdentifier)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (signingKeyIdentifier == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signingKeyIdentifier");
            }

            if (KeyInfoSerializer.CanWriteKeyIdentifier(signingKeyIdentifier))
            {
                KeyInfoSerializer.WriteKeyIdentifier(writer, signingKeyIdentifier);
                return;
            }

            throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4221, signingKeyIdentifier));
        }

        /// <summary>
        /// Validates the subject in each statement in the collection of Saml statements.
        /// </summary>
        /// <param name="statements"></param>
        private void ValidateStatements(IList<SamlStatement> statements)
        {
            if (statements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("statements");
            }
            List<SamlSubject> subjects = new List<SamlSubject>();
            foreach (SamlStatement statement in statements)
            {
                if (statement is SamlAttributeStatement)
                {
                    subjects.Add((statement as SamlAttributeStatement).SamlSubject);
                }

                if (statement is SamlAuthenticationStatement)
                {
                    subjects.Add((statement as SamlAuthenticationStatement).SamlSubject);
                }

                if (statement is SamlAuthorizationDecisionStatement)
                {
                    subjects.Add((statement as SamlAuthorizationDecisionStatement).SamlSubject);
                }
                //
                // skip all custom statements
                //

            }

            if (subjects.Count == 0)
            {
                //
                // All statements are custom and we cannot validate
                //
                return;
            }
            string requiredSubjectName = subjects[0].Name;
            string requiredSubjectFormat = subjects[0].NameFormat;
            string requiredSubjectQualifier = subjects[0].NameQualifier;

            foreach (SamlSubject subject in subjects)
            {
                if (!StringComparer.Ordinal.Equals(subject.Name, requiredSubjectName) ||
                     !StringComparer.Ordinal.Equals(subject.NameFormat, requiredSubjectFormat) ||
                     !StringComparer.Ordinal.Equals(subject.NameQualifier, requiredSubjectQualifier))
                {
                    //
                    // The SamlSubjects in the statements do not match
                    //
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4225, subject));
                }
            }
        }

        #endregion

        /// <summary>
        /// Returns the saml token's token type that is supported by this handler.
        /// </summary>
        public override string[] GetTokenTypeIdentifiers()
        {
            return _tokenTypeIdentifiers;
        }

        /// <summary>
        /// Gets or Sets a SecurityTokenSerializers that will be used to serialize and deserializer
        /// SecurtyKeyIdentifier. For example, SamlSubject SecurityKeyIdentifier or Signature 
        /// SecurityKeyIdentifier.
        /// </summary>
        public SecurityTokenSerializer KeyInfoSerializer
        {
            get
            {
                if (_keyInfoSerializer == null)
                {
                    lock (_syncObject)
                    {
                        if (_keyInfoSerializer == null)
                        {
                            SecurityTokenHandlerCollection sthc = (ContainingCollection != null) ?
                                ContainingCollection : SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                            _keyInfoSerializer = new SecurityTokenSerializerAdapter(sthc);
                        }
                    }
                }

                return _keyInfoSerializer;
            }
            set
            {
                if (value == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
                }

                _keyInfoSerializer = value;
            }
        }

        /// <summary>
        /// Gets the System.Type of the SecurityToken is supported by ththis handler.
        /// </summary>
        public override Type TokenType
        {
            get { return typeof(SamlSecurityToken); }
        }

        /// <summary>
        /// Gets or sets the <see cref="SamlSecurityTokenRequirement"/>
        /// </summary>
        public SamlSecurityTokenRequirement SamlSecurityTokenRequirement
        {
            get
            {
                return _samlSecurityTokenRequirement;
            }
            set
            {
                if (value == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
                }
                _samlSecurityTokenRequirement = value;
            }
        }

        // This thin wrapper is used to pass a serializer down into the 
        // EnvelopedSignatureReader that will use the Saml11SecurityTokenHandlers's
        // ReadKeyInfo method to read the KeyInfo.
        class WrappedSerializer : SecurityTokenSerializer
        {
            SamlSecurityTokenHandler _parent;
            SamlAssertion _assertion;

            public WrappedSerializer(SamlSecurityTokenHandler parent, SamlAssertion assertion)
            {
                if (parent == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
                }

                _parent = parent;
                _assertion = assertion;
            }

            protected override bool CanReadKeyIdentifierClauseCore(XmlReader reader)
            {
                return false;
            }

            protected override bool CanReadKeyIdentifierCore(XmlReader reader)
            {
                return true;
            }

            protected override bool CanReadTokenCore(XmlReader reader)
            {
                return false;
            }

            protected override bool CanWriteKeyIdentifierClauseCore(SecurityKeyIdentifierClause keyIdentifierClause)
            {
                return false;
            }

            protected override bool CanWriteKeyIdentifierCore(SecurityKeyIdentifier keyIdentifier)
            {
                return false;
            }

            protected override bool CanWriteTokenCore(SecurityToken token)
            {
                return false;
            }

            protected override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlReader reader)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }

            protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader)
            {
                return _parent.ReadSigningKeyInfo(reader, _assertion);
            }

            protected override SecurityToken ReadTokenCore(XmlReader reader, SecurityTokenResolver tokenResolver)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }

            protected override void WriteKeyIdentifierClauseCore(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }

            protected override void WriteKeyIdentifierCore(XmlWriter writer, SecurityKeyIdentifier keyIdentifier)
            {
                _parent.WriteSigningKeyInfo(writer, keyIdentifier);
            }

            protected override void WriteTokenCore(XmlWriter writer, SecurityToken token)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }
        }
    }
}