File: SecurityTokenHandlerCollection.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (723 lines) | stat: -rw-r--r-- 28,559 bytes parent folder | download | duplicates (7)
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
//-----------------------------------------------------------------------
// <copyright file="SecurityTokenHandlerCollection.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace System.IdentityModel.Tokens
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IdentityModel.Selectors;
    using System.Security.Claims;
    using System.Xml;

    /// <summary>
    /// Defines a collection of SecurityTokenHandlers.
    /// </summary>
    public class SecurityTokenHandlerCollection : Collection<SecurityTokenHandler>
    {
        internal static int defaultHandlerCollectionCount = 8;

        private Dictionary<string, SecurityTokenHandler> handlersByIdentifier = new Dictionary<string, SecurityTokenHandler>();
        private Dictionary<Type, SecurityTokenHandler> handlersByType = new Dictionary<Type, SecurityTokenHandler>();

        private SecurityTokenHandlerConfiguration configuration;

        private KeyInfoSerializer keyInfoSerializer;

        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>.
        /// Creates an empty set.
        /// </summary>
        public SecurityTokenHandlerCollection()
            : this(new SecurityTokenHandlerConfiguration())
        {
        }

        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>.
        /// Creates an empty set.
        /// </summary>
        /// <param name="configuration">The configuration to associate with the collection.</param>
        public SecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
        {
            if (configuration == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("configuration");
            }

            this.configuration = configuration;
            this.keyInfoSerializer = new KeyInfoSerializer(true);
        }

        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>
        /// </summary>
        /// <param name="handlers">List of SecurityTokenHandlers to initialize from.</param>
        /// <remarks>
        /// Do not use this constructor to attempt to clone an instance of a SecurityTokenHandlerCollection,
        /// use the Clone method instead.
        /// </remarks>
        public SecurityTokenHandlerCollection(IEnumerable<SecurityTokenHandler> handlers)
            : this(handlers, new SecurityTokenHandlerConfiguration())
        {
        }

        /// <summary>
        /// Creates an instance of <see cref="SecurityTokenHandlerCollection"/>
        /// </summary>
        /// <param name="handlers">List of SecurityTokenHandlers to initialize from.</param>
        /// <param name="configuration">The <see cref="SecurityTokenHandlerConfiguration"/> in effect.</param>
        /// <remarks>
        /// Do not use this constructor to attempt to clone an instance of a SecurityTokenHandlerCollection,
        /// use the Clone method instead.
        /// </remarks>
        public SecurityTokenHandlerCollection(IEnumerable<SecurityTokenHandler> handlers, SecurityTokenHandlerConfiguration configuration)
            : this(configuration)
        {
            if (handlers == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("handlers");
            }

            foreach (SecurityTokenHandler handler in handlers)
            {
                Add(handler);
            }
        }

        /// <summary>
        /// Gets an instance of <see cref="SecurityTokenHandlerConfiguration"/>
        /// </summary>
        public SecurityTokenHandlerConfiguration Configuration
        {
            get { return this.configuration; }
        }

        /// <summary>
        /// Gets the List of System.Type of the Token Handlers in this collection.
        /// </summary>
        public IEnumerable<Type> TokenTypes
        {
            get { return this.handlersByType.Keys; }
        }

        /// <summary>
        /// Gets the list of Token type Identifier of the Token Handlers.
        /// </summary>
        public IEnumerable<string> TokenTypeIdentifiers
        {
            get
            {
                return this.handlersByIdentifier.Keys;
            }
        }

        /// <summary>
        /// Gets a Token Handler by its Token Type Identifier.
        /// </summary>
        /// <param name="tokenTypeIdentifier">The Token Type Identfier string to search for.</param>
        /// <returns>Instance of a SecurityTokenHandler.</returns>
        public SecurityTokenHandler this[string tokenTypeIdentifier]
        {
            get
            {
                if (string.IsNullOrEmpty(tokenTypeIdentifier))
                {
                    return null;
                }

                SecurityTokenHandler handler;
                this.handlersByIdentifier.TryGetValue(tokenTypeIdentifier, out handler);
                return handler;
            }
        }

        /// <summary>
        /// Gets a Token Handler that can handle a given SecurityToken.
        /// </summary>
        /// <param name="token">SecurityToken for which a Token Handler is requested.</param>
        /// <returns>Instance of SecurityTokenHandler.</returns>
        public SecurityTokenHandler this[SecurityToken token]
        {
            get
            {
                if (null == token)
                {
                    return null;
                }

                return this[token.GetType()];
            }
        }

        /// <summary>
        /// Gets a Token Handler based on the System.Type of the token.
        /// </summary>
        /// <param name="tokenType">System.Type of the Token that needs to be handled.</param>
        /// <returns>Instance of SecurityTokenHandler.</returns>
        public SecurityTokenHandler this[Type tokenType]
        {
            get
            {
                SecurityTokenHandler handler = null;
                if (tokenType != null)
                {
                    this.handlersByType.TryGetValue(tokenType, out handler);
                }

                return handler;
            }
        }

        /// <summary>
        /// Creates a system default collection of basic SecurityTokenHandlers, each of which has the system default configuration.
        /// The SecurityTokenHandlers in this collection must be configured with service specific data before they can be used.
        /// </summary>
        /// <returns>A SecurityTokenHandlerCollection with default basic SecurityTokenHandlers.</returns>
        public static SecurityTokenHandlerCollection CreateDefaultSecurityTokenHandlerCollection()
        {
            return CreateDefaultSecurityTokenHandlerCollection(new SecurityTokenHandlerConfiguration());
        }

        /// <summary>
        /// Creates a system default collection of basic SecurityTokenHandlers, each of which has the system default configuration.
        /// The SecurityTokenHandlers in this collection must be configured with service specific data before they can be used.
        /// </summary>
        /// <param name="configuration">The configuration to associate with the collection.</param>
        /// <returns>A SecurityTokenHandlerCollection with default basic SecurityTokenHandlers.</returns>
        public static SecurityTokenHandlerCollection CreateDefaultSecurityTokenHandlerCollection(SecurityTokenHandlerConfiguration configuration)
        {

            SecurityTokenHandlerCollection collection = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] {
                                                                                                 new KerberosSecurityTokenHandler(),
                                                                                                 new RsaSecurityTokenHandler(),
                                                                                                 new SamlSecurityTokenHandler(), 
                                                                                                 new Saml2SecurityTokenHandler(),
                                                                                                 new WindowsUserNameSecurityTokenHandler(),
                                                                                                 new X509SecurityTokenHandler(),
                                                                                                 new EncryptedSecurityTokenHandler(),
                                                                                                 new SessionSecurityTokenHandler(),
                                                                                                },
                                                                                             configuration);

            defaultHandlerCollectionCount = collection.Count;

            return collection;
        }

        internal SecurityTokenSerializer KeyInfoSerializer
        {
            get { return this.keyInfoSerializer; }
        }

        /// <summary>
        /// Adds a new handler or replace the existing handler with the same token type identifier 
        /// with with the new handler.
        /// </summary>
        /// <param name="handler">The SecurityTokenHandler to add or replace</param>
        /// <exception cref="ArgumentNullException">When the input parameter is null.</exception>
        public void AddOrReplace(SecurityTokenHandler handler)
        {
            if (handler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("handler");
            }

            // Remove the old one if it exists
            Type tokenType = handler.TokenType;
            if (tokenType != null && this.handlersByType.ContainsKey(tokenType))
            {
                Remove(this[tokenType]);
            }
            else
            {
                string[] identifiers = handler.GetTokenTypeIdentifiers();
                if (identifiers != null)
                {
                    foreach (string tokenTypeIdentifier in identifiers)
                    {
                        if (tokenTypeIdentifier != null && this.handlersByIdentifier.ContainsKey(tokenTypeIdentifier))
                        {
                            Remove(this[tokenTypeIdentifier]);
                            break;
                        }
                    }
                }
            }

            // Add the new handler in the collection
            Add(handler);
        }

        /// <summary>
        /// Checks if a token can be read using the SecurityTokenHandlers.
        /// </summary>
        /// <param name="reader">XmlReader pointing at token.</param>
        /// <returns>True if the token can be read, false otherwise</returns>
        /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception>
        public bool CanReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            foreach (SecurityTokenHandler handler in this)
            {
                if (null != handler && handler.CanReadToken(reader))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Checks if a token can be read using the SecurityTokenHandlers.
        /// </summary>
        /// <param name="tokenString">The token string thats needs to be read.</param>
        /// <returns>True if the token can be read, false otherwise</returns>
        /// <exception cref="ArgumentException">The input argument 'tokenString' is null or empty.</exception>
        public bool CanReadToken(string tokenString)
        {
            if (String.IsNullOrEmpty(tokenString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNullOrEmptyString("tokenString");
            }

            foreach (SecurityTokenHandler handler in this)
            {
                if (null != handler && handler.CanReadToken(tokenString))
                {
                    return true;
                }
            }

            return false;
        }
        
        /// <summary>
        /// Checks if a token can be written using the SecurityTokenHandlers.
        /// </summary>
        /// <param name="token">SecurityToken to be written out.</param>
        /// <returns>True if the token can be written, false otherwise</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        public bool CanWriteToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SecurityTokenHandler handler = this[token];
            if (null != handler && handler.CanWriteToken)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Creates a SecurityToken from the given SecurityTokenDescriptor using the list of
        /// SecurityTokenHandlers.
        /// </summary>
        /// <param name="tokenDescriptor">SecurityTokenDescriptor for the token to be created.</param>
        /// <returns>Instance of <see cref="SecurityToken"/></returns>
        /// <exception cref="ArgumentNullException">The input argument 'tokenDescriptor' is null.</exception>
        public SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenDescriptor");
            }

            SecurityTokenHandler handler = this[tokenDescriptor.TokenType];
            if (null == handler)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4020, tokenDescriptor.TokenType)));
            }

            return handler.CreateToken(tokenDescriptor);
        }

        /// <summary>
        /// Validates a given token using the SecurityTokenHandlers.
        /// </summary>
        /// <param name="token">The SecurityToken to be validated.</param>
        /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        /// <exception cref="InvalidOperationException">A <see cref="SecurityTokenHandler"/> cannot be found that can validate the <see cref="SecurityToken"/>.</exception>                
        public ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SecurityTokenHandler handler = this[token];
            if (null == handler || !handler.CanValidateToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4011, token.GetType())));
            }

            return handler.ValidateToken(token);
        }

        /// <summary>
        /// Reads a token using the TokenHandlers.
        /// </summary>
        /// <param name="reader">XmlReader pointing at token.</param>
        /// <returns>Instance of <see cref="SecurityToken"/></returns>
        /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception>
        public SecurityToken ReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            foreach (SecurityTokenHandler handler in this)
            {
                if (null != handler && handler.CanReadToken(reader))
                {
                    return handler.ReadToken(reader);
                }
            }

            return null;
        }

        /// <summary>
        /// Reads a token using the TokenHandlers.
        /// </summary>
        /// <param name="tokenString">The token string to be deserialized.</param>
        /// <returns>Instance of <see cref="SecurityToken"/></returns>
        /// <exception cref="ArgumentException">The input argument 'tokenString' is null or empty.</exception>
        public SecurityToken ReadToken(string tokenString)
        {
            if (String.IsNullOrEmpty(tokenString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNullOrEmptyString("tokenString");
            }

            foreach (SecurityTokenHandler handler in this)
            {
                if (null != handler && handler.CanReadToken(tokenString))
                {
                    return handler.ReadToken(tokenString);
                }
            }

            return null;
        }

        /// <summary>
        /// Writes a given SecurityToken to the XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to write the token into.</param>
        /// <param name="token">SecurityToken to be written out.</param>
        /// <exception cref="ArgumentNullException">The input argument 'writer' or 'token' is null.</exception>
        public void WriteToken(XmlWriter writer, SecurityToken token)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

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

            SecurityTokenHandler handler = this[token];
            if (null == handler || !handler.CanWriteToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4010, token.GetType())));
            }

            handler.WriteToken(writer, token);
        }

        /// <summary>
        /// Writes a given SecurityToken to a string.
        /// </summary>
        /// <param name="token">SecurityToken to be written out.</param>
        /// <returns>The serialized token.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'token' is null.</exception>
        public string WriteToken(SecurityToken token)
        {
            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token");
            }

            SecurityTokenHandler handler = this[token];
            if (null == handler || !handler.CanWriteToken)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4010, token.GetType())));
            }

            return handler.WriteToken(token);
        }

        /// <summary>
        /// Override. (Inherited from Collection&lt;T>"/>
        /// </summary>
        protected override void ClearItems()
        {
            base.ClearItems();
            this.handlersByIdentifier.Clear();
            this.handlersByType.Clear();
        }

        /// <summary>
        /// Override. (Inherited from Collection&lt;T&gt;"/>
        /// </summary>
        /// <param name="index">The zero-based index at which item should be inserted.</param>
        /// <param name="item">The object to insert. The value can be null for reference types.</param>
        protected override void InsertItem(int index, SecurityTokenHandler item)
        {
            base.InsertItem(index, item);

            try
            {
                this.AddToDictionaries(item);
            }
            catch
            {
                base.RemoveItem(index);
                throw;
            }
        }

        /// <summary>
        /// Override. (Inherited from Collection&lt;T>"/>
        /// </summary>
        /// <param name="index">The zero-based index of the element to remove.</param>
        protected override void RemoveItem(int index)
        {
            SecurityTokenHandler removedItem = Items[index];
            base.RemoveItem(index);
            this.RemoveFromDictionaries(removedItem);
        }

        /// <summary>
        /// Override. (Inherited from Collection&lt;T>"/>
        /// </summary>
        /// <param name="index">The zero-based index of the element to replace.</param>
        /// <param name="item">The new value for the element at the specified index. The value can be null for reference types.</param>
        protected override void SetItem(int index, SecurityTokenHandler item)
        {
            SecurityTokenHandler replaced = Items[index];
            base.SetItem(index, item);

            this.RemoveFromDictionaries(replaced);

            try
            {
                this.AddToDictionaries(item);
            }
            catch
            {
                base.SetItem(index, replaced);
                this.AddToDictionaries(replaced);
                throw;
            }
        }

        public bool CanReadKeyIdentifierClause(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            return CanReadKeyIdentifierClauseCore(reader);
        }

        /// <summary>
        /// Checks if the wrapped SecurityTokenHandler or the base WSSecurityTokenSerializer can read the 
        /// SecurityKeyIdentifierClause.
        /// </summary>
        /// <param name="reader">Reader to a SecurityKeyIdentifierClause.</param>
        /// <returns>'True' if the SecurityKeyIdentifierCause can be read.</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        protected virtual bool CanReadKeyIdentifierClauseCore(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            foreach (SecurityTokenHandler securityTokenHandler in this)
            {
                if (securityTokenHandler.CanReadKeyIdentifierClause(reader))
                {
                    return true;
                }
            }

            return false;
        }

        public SecurityKeyIdentifierClause ReadKeyIdentifierClause(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            return ReadKeyIdentifierClauseCore(reader);
        }

        /// <summary>
        /// Deserializes a SecurityKeyIdentifierClause from the given reader.
        /// </summary>
        /// <param name="reader">XmlReader to a SecurityKeyIdentifierClause.</param>
        /// <returns>The deserialized SecurityKeyIdentifierClause.</returns>
        /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception>
        protected virtual SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            foreach (SecurityTokenHandler securityTokenHandler in this)
            {
                if (securityTokenHandler.CanReadKeyIdentifierClause(reader))
                {
                    return securityTokenHandler.ReadKeyIdentifierClause(reader);
                }
            }

            return this.keyInfoSerializer.ReadKeyIdentifierClause(reader);
        }

        public void WriteKeyIdentifierClause(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

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

            WriteKeyIdentifierClauseCore(writer, keyIdentifierClause);
        }

        /// <summary>
        /// Serializes the given SecurityKeyIdentifierClause in a XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to write into.</param>
        /// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to be written.</param>
        /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'keyIdentifierClause' is null.</exception>
        protected virtual void WriteKeyIdentifierClauseCore(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

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

            foreach (SecurityTokenHandler securityTokenHandler in this)
            {
                if (securityTokenHandler.CanWriteKeyIdentifierClause(keyIdentifierClause))
                {
                    securityTokenHandler.WriteKeyIdentifierClause(writer, keyIdentifierClause);
                    return;
                }
            }

            this.keyInfoSerializer.WriteKeyIdentifierClause(writer, keyIdentifierClause);
        }

        private void AddToDictionaries(SecurityTokenHandler handler)
        {
            if (handler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("handler");
            }

            bool firstSucceeded = false;

            string[] identifiers = handler.GetTokenTypeIdentifiers();
            if (identifiers != null)
            {
                foreach (string typeId in identifiers)
                {
                    if (typeId != null)
                    {
                        this.handlersByIdentifier.Add(typeId, handler);
                        firstSucceeded = true;
                    }
                }
            }

            Type type = handler.TokenType;
            if (handler.TokenType != null)
            {
                try
                {
                    this.handlersByType.Add(type, handler);
                }
                catch
                {
                    if (firstSucceeded)
                    {
                        this.RemoveFromDictionaries(handler);
                    }

                    throw;
                }
            }

            // Ensure that the handler knows which collection it is in.
            handler.ContainingCollection = this;

            // Propagate this collection's STH configuration to the handler
            // if the handler's configuration is unset.
            if (handler.Configuration == null)
            {
                handler.Configuration = this.configuration;
            }
        }

        private void RemoveFromDictionaries(SecurityTokenHandler handler)
        {
            string[] identifiers = handler.GetTokenTypeIdentifiers();
            if (identifiers != null)
            {
                foreach (string typeId in identifiers)
                {
                    if (typeId != null)
                    {
                        this.handlersByIdentifier.Remove(typeId);
                    }
                }
            }

            Type type = handler.TokenType;
            if (type != null && this.handlersByType.ContainsKey(type))
            {
                this.handlersByType.Remove(type);
            }

            // Ensure that the handler knows that it is no longer
            // in a collection.
            handler.ContainingCollection = null;
            handler.Configuration = null;
        }
    }
}