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

FederatedSecurityTokenManager.cs « Security « ServiceModel « System « System.ServiceModel « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4cd988b21cd342f122d68e068d495c32490e57dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Description;
using System.ServiceModel.Security.Tokens;

using SR = System.ServiceModel.SR;


namespace System.ServiceModel.Security
{
    /// <summary>
    /// SecurityTokenManager that enables plugging custom tokens easily.
    /// The SecurityTokenManager provides methods to register custom token providers,
    /// serializers and authenticators. It can wrap another Token Managers and
    /// delegate token operation calls to it if required.
    /// </summary>
    /// <remarks>
    /// Framework use only - this is an implementation adapter class that is used to expose
    /// the Framework SecurityTokenHandlers to WCF.
    /// </remarks>
    sealed class FederatedSecurityTokenManager : ServiceCredentialsSecurityTokenManager
    {
        static string ListenUriProperty = "http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/ListenUri";

        ExceptionMapper _exceptionMapper;
        SecurityTokenResolver _defaultTokenResolver;

        SecurityTokenHandlerCollection _securityTokenHandlerCollection;
        object _syncObject = new object();

        ReadOnlyCollection<CookieTransform> _cookieTransforms;
        SessionSecurityTokenCache _tokenCache;

        /// <summary>
        /// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
        /// </summary>
        /// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
        /// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
        public FederatedSecurityTokenManager( ServiceCredentials parentCredentials )
            : base( parentCredentials )
        {
            if ( parentCredentials == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials" );
            }

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

            _exceptionMapper = parentCredentials.ExceptionMapper;

            _securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;                        
            _tokenCache = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;                        
            _cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
        }

        /// <summary>
        /// Returns the list of SecurityTokenHandlers.
        /// </summary>
        public SecurityTokenHandlerCollection SecurityTokenHandlers
        {
            //
            // 


            get { return _securityTokenHandlerCollection; }
        }

        /// <summary>
        /// Gets or sets the ExceptionMapper to be used when throwing exceptions.
        /// </summary>
        public ExceptionMapper ExceptionMapper
        {
            get
            {
                return _exceptionMapper;
            }
            set
            {
                if ( value == null )
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "value" );
                }
                _exceptionMapper = value;
            }
        }

        #region SecurityTokenManager Implementation

        /// <summary>
        /// Overriden from the base class. Creates the requested Token Authenticator.
        /// Looks up the list of Token Handlers registered with the token Manager
        /// based on the TokenType Uri in the SecurityTokenRequirement. If none is found,
        /// then the call is delegated to the inner Token Manager.
        /// </summary>
        /// <param name="tokenRequirement">Security Token Requirement for which the Authenticator should be created.</param>
        /// <param name="outOfBandTokenResolver">Token resolver that resolves any out-of-band tokens.</param>
        /// <returns>Instance of Security Token Authenticator.</returns>
        /// <exception cref="ArgumentNullException">'tokenRequirement' parameter is null.</exception>
        /// <exception cref="NotSupportedException">No Authenticator is registered for the given token type.</exception>
        public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
        {
            if ( tokenRequirement == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
            }

            outOfBandTokenResolver = null;

            // Check for a registered authenticator
            SecurityTokenAuthenticator securityTokenAuthenticator = null;

            string tokenType = tokenRequirement.TokenType;

            //
            // When the TokenRequirement.TokenType is null, we treat this as a SAML issued token case. It may be SAML 1.1 or SAML 2.0.
            //
            if ( String.IsNullOrEmpty( tokenType ) )
            {
                return CreateSamlSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
            }

            //
            // When the TokenType is set, build a token authenticator for the specified token type.
            //
            SecurityTokenHandler securityTokenHandler = _securityTokenHandlerCollection[tokenType];
            if ( ( securityTokenHandler != null ) && ( securityTokenHandler.CanValidateToken ) )
            {
                outOfBandTokenResolver = GetDefaultOutOfBandTokenResolver();

                if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.UserName ) )
                {
                    UserNameSecurityTokenHandler upSecurityTokenHandler = securityTokenHandler as UserNameSecurityTokenHandler;
                    if ( upSecurityTokenHandler == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( UserNameSecurityTokenHandler ) ) ) );
                    }
                    securityTokenAuthenticator = new WrappedUserNameSecurityTokenAuthenticator( upSecurityTokenHandler, _exceptionMapper );
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Kerberos ) )
                {
                    securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Rsa ) )
                {
                    RsaSecurityTokenHandler rsaSecurityTokenHandler = securityTokenHandler as RsaSecurityTokenHandler;
                    if ( rsaSecurityTokenHandler == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( RsaSecurityTokenHandler ) ) ) );
                    }
                    securityTokenAuthenticator = new WrappedRsaSecurityTokenAuthenticator( rsaSecurityTokenHandler, _exceptionMapper );
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.X509Certificate ) )
                {
                    X509SecurityTokenHandler x509SecurityTokenHandler = securityTokenHandler as X509SecurityTokenHandler;
                    if ( x509SecurityTokenHandler == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( X509SecurityTokenHandler ) ) ) );
                    }
                    securityTokenAuthenticator = new WrappedX509SecurityTokenAuthenticator( x509SecurityTokenHandler, _exceptionMapper );
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.SamlTokenProfile11 ) ||
                          StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSamlTokenProfile11 ) )
                {
                    SamlSecurityTokenHandler saml11SecurityTokenHandler = securityTokenHandler as SamlSecurityTokenHandler;
                    if ( saml11SecurityTokenHandler == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( SamlSecurityTokenHandler ) ) ) );
                    }

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

                    securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
                    // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                    outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Saml2TokenProfile11 ) ||
                          StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSaml2TokenProfile11 ) )
                {
                    Saml2SecurityTokenHandler saml2SecurityTokenHandler = securityTokenHandler as Saml2SecurityTokenHandler;
                    if ( saml2SecurityTokenHandler == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( Saml2SecurityTokenHandler ) ) ) );
                    }

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

                    securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
                    // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                    outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
                }
                else if ( StringComparer.Ordinal.Equals( tokenType, ServiceModelSecurityTokenTypes.SecureConversation ) )
                {
                    RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
                    if ( tr == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
                    }

                    securityTokenAuthenticator = SetupSecureConversationWrapper( tr, securityTokenHandler as SessionSecurityTokenHandler, out outOfBandTokenResolver );
                }
                else
                {
                    securityTokenAuthenticator = new SecurityTokenAuthenticatorAdapter( securityTokenHandler, _exceptionMapper );
                }
            }
            else
            {
                if ( tokenType == ServiceModelSecurityTokenTypes.SecureConversation
                    || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
                    || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
                    || tokenType == ServiceModelSecurityTokenTypes.SecurityContext
                    || tokenType == ServiceModelSecurityTokenTypes.Spnego )
                {
                    RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
                    if ( tr == null )
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
                    }

                    securityTokenAuthenticator = SetupSecureConversationWrapper( tr, null, out outOfBandTokenResolver );
                }
                else
                {
                    securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
                }
            }

            return securityTokenAuthenticator;
        }

        /// <summary>
        /// Helper method to setup the WrappedSecureConversttion
        /// </summary>
        SecurityTokenAuthenticator SetupSecureConversationWrapper( RecipientServiceModelSecurityTokenRequirement tokenRequirement, SessionSecurityTokenHandler tokenHandler, out SecurityTokenResolver outOfBandTokenResolver )
        {
            // This code requires Orcas SP1 to compile.
            // WCF expects this securityTokenAuthenticator to support:
            // 1. IIssuanceSecurityTokenAuthenticator
            // 2. ICommunicationObject is needed for this to work right.
            // WCF opens a listener in this STA that handles the nego and uses an internal class for negotiating the 
            // the bootstrap tokens.  We want to handle ValidateToken to return our authorization policies and surface the bootstrap tokens.

            // when sp1 is installed, use this one.
            //SecurityTokenAuthenticator sta = base.CreateSecureConversationTokenAuthenticator( tokenRequirement as RecipientServiceModelSecurityTokenRequirement, _saveBootstrapTokensInSession, out outOfBandTokenResolver );

            // use this code if SP1 is not installed
            SecurityTokenAuthenticator sta = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
            SessionSecurityTokenHandler sessionTokenHandler = tokenHandler;

            //
            // If there is no SCT handler here, create one.
            //
            if ( tokenHandler == null )
            {
                sessionTokenHandler = new SessionSecurityTokenHandler( _cookieTransforms, SessionSecurityTokenHandler.DefaultTokenLifetime );
                sessionTokenHandler.ContainingCollection = _securityTokenHandlerCollection;
                sessionTokenHandler.Configuration = _securityTokenHandlerCollection.Configuration;
            }

            if ( ServiceCredentials != null )
            {
                sessionTokenHandler.Configuration.MaxClockSkew = ServiceCredentials.IdentityConfiguration.MaxClockSkew;
            }

            SctClaimsHandler claimsHandler = new SctClaimsHandler(
                                                    _securityTokenHandlerCollection,
                                                    GetNormalizedEndpointId( tokenRequirement ) );

            WrappedSessionSecurityTokenAuthenticator wssta = new WrappedSessionSecurityTokenAuthenticator( sessionTokenHandler, sta,
                                                                                                           claimsHandler, _exceptionMapper );
            WrappedTokenCache wrappedTokenCache = new WrappedTokenCache( _tokenCache, claimsHandler);
            SetWrappedTokenCache( wrappedTokenCache, sta, wssta, claimsHandler );
            outOfBandTokenResolver = wrappedTokenCache;

            return wssta;
        }

        /// <summary>
        /// The purpose of this method is to set our WrappedTokenCache as the token cache for SCT's.
        /// And to set our OnIssuedToken callback when in cookie mode.
        /// We have to use reflection here as this is a private method.
        /// </summary>
        static void SetWrappedTokenCache(
            WrappedTokenCache wrappedTokenCache,
            SecurityTokenAuthenticator sta,
            WrappedSessionSecurityTokenAuthenticator wssta,
            SctClaimsHandler claimsHandler )
        {
            if ( sta is SecuritySessionSecurityTokenAuthenticator )
            {
                ( sta as SecuritySessionSecurityTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
            }
            else if ( sta is AcceleratedTokenAuthenticator )
            {
                ( sta as AcceleratedTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
            }
            else if ( sta is SpnegoTokenAuthenticator )
            {
                ( sta as SpnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
            }
            else if ( sta is TlsnegoTokenAuthenticator )
            {
                ( sta as TlsnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
            }

            // we need to special case this as the OnTokenIssued callback is not hooked up in the cookie mode case.
            IIssuanceSecurityTokenAuthenticator issuanceTokenAuthenticator = sta as IIssuanceSecurityTokenAuthenticator;
            if ( issuanceTokenAuthenticator != null )
            {
                issuanceTokenAuthenticator.IssuedSecurityTokenHandler = claimsHandler.OnTokenIssued;
                issuanceTokenAuthenticator.RenewedSecurityTokenHandler = claimsHandler.OnTokenRenewed;
            }
        }

        /// <summary>
        /// Overriden from the base class. Creates the requested Token Serializer.
        /// Returns a Security Token Serializer that is wraps the list of token
        /// hanlders registerd and also the serializers from the inner token manager.
        /// </summary>
        /// <param name="version">SecurityTokenVersion of the serializer to be created.</param>
        /// <returns>Instance of SecurityTokenSerializer.</returns>
        /// <exception cref="ArgumentNullException">Input parameter is null.</exception>
        public override SecurityTokenSerializer CreateSecurityTokenSerializer( SecurityTokenVersion version )
        {
            if ( version == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "version" );
            }

            TrustVersion trustVersion = null;
            SecureConversationVersion scVersion = null;

            foreach ( string securitySpecification in version.GetSecuritySpecifications() )
            {
                if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrustFeb2005Constants.NamespaceURI ) )
                {
                    trustVersion = TrustVersion.WSTrustFeb2005;
                }
                else if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrust13Constants.NamespaceURI ) )
                {
                    trustVersion = TrustVersion.WSTrust13;
                }
                else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversationFeb2005Constants.Namespace ) )
                {
                    scVersion = SecureConversationVersion.WSSecureConversationFeb2005;
                }
                else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversation13Constants.Namespace ) )
                {
                    scVersion = SecureConversationVersion.WSSecureConversation13;
                }

                if ( trustVersion != null && scVersion != null )
                {
                    break;
                }
            }

            if ( trustVersion == null )
            {
                trustVersion = TrustVersion.WSTrust13;
            }

            if ( scVersion == null )
            {
                scVersion = SecureConversationVersion.WSSecureConversation13;
            }

            WsSecurityTokenSerializerAdapter adapter = new WsSecurityTokenSerializerAdapter( _securityTokenHandlerCollection,
                GetSecurityVersion( version ), trustVersion, scVersion, false, this.ServiceCredentials.IssuedTokenAuthentication.SamlSerializer,
                this.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder,
                this.ServiceCredentials.SecureConversationAuthentication.SecurityContextClaimTypes );

            adapter.MapExceptionsToSoapFaults = true;
            adapter.ExceptionMapper = _exceptionMapper;

            return adapter;
        }

        /// <summary>
        /// The out-of-band token resolver to be used if the authenticator does
        /// not provide another.
        /// </summary>
        /// <remarks>By default this will create the resolver with the service certificate and 
        /// know certificates collections specified in the service credentials when the STS is 
        /// hosted inside WCF.</remarks>
        SecurityTokenResolver GetDefaultOutOfBandTokenResolver()
        {
            if ( _defaultTokenResolver == null )
            {
                lock ( _syncObject )
                {
                    if ( _defaultTokenResolver == null )
                    {
                        // 
                        // Create default Out-Of-Band SecurityResolver.
                        //
                        List<SecurityToken> outOfBandTokens = new List<SecurityToken>();
                        if ( base.ServiceCredentials.ServiceCertificate.Certificate != null )
                        {
                            outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.ServiceCertificate.Certificate ) );
                        }

                        if ( ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates != null ) && ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count > 0 ) )
                        {
                            for ( int i = 0; i < base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count; ++i )
                            {
                                outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates[i]));
                            }
                        }

                        _defaultTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( outOfBandTokens.AsReadOnly(), false );
                    }
                }
            }

            return _defaultTokenResolver;
        }
        /// <summary>
        /// There is a 


        internal static SecurityVersion GetSecurityVersion( SecurityTokenVersion tokenVersion )
        {
            if ( tokenVersion == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenVersion" );
            }

            //
            // Workaround for WCF 




            if ( tokenVersion is MessageSecurityTokenVersion )
            {
                SecurityVersion sv = ( tokenVersion as MessageSecurityTokenVersion ).SecurityVersion;

                if ( sv != null )
                {
                    return sv;
                }
            }
            else
            {
                if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity11Constants.Namespace ) )
                {
                    return SecurityVersion.WSSecurity11;
                }
                else if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity10Constants.Namespace ) )
                {
                    return SecurityVersion.WSSecurity10;
                }
            }

            return SecurityVersion.WSSecurity11;
        }

        #endregion // SecurityTokenManager Implementation

        /// <summary>
        /// This method creates the inner security token authenticator from the base class.
        /// The wrapped token cache is initialized with this authenticator.
        /// </summary>
        SecurityTokenAuthenticator CreateInnerSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
        {
            SecurityTokenAuthenticator securityTokenAuthenticator = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
            SctClaimsHandler claimsHandler = new SctClaimsHandler(
                                        _securityTokenHandlerCollection,
                                        GetNormalizedEndpointId( tokenRequirement ) );
            
            SetWrappedTokenCache( new WrappedTokenCache( _tokenCache, claimsHandler ), securityTokenAuthenticator, null, claimsHandler );
            return securityTokenAuthenticator;
        }

        /// <summary>
        /// This method creates a SAML security token authenticator when token type is null.
        /// It wraps the SAML 1.1 and the SAML 2.0 token handlers that are configured.
        /// If no token handler was found, then the inner token manager is created.
        /// </summary>
        SecurityTokenAuthenticator CreateSamlSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
        {
            outOfBandTokenResolver = null;

            SecurityTokenAuthenticator securityTokenAuthenticator = null;

            SamlSecurityTokenHandler saml11SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.SamlTokenProfile11] as SamlSecurityTokenHandler;
            Saml2SecurityTokenHandler saml2SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.Saml2TokenProfile11] as Saml2SecurityTokenHandler;

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

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

            if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler != null )
            {
                //
                // Both SAML 1.1 and SAML 2.0 token handlers have been configured.
                //

                WrappedSaml11SecurityTokenAuthenticator wrappedSaml11SecurityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
                WrappedSaml2SecurityTokenAuthenticator wrappedSaml2SecurityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );

                securityTokenAuthenticator = new WrappedSamlSecurityTokenAuthenticator( wrappedSaml11SecurityTokenAuthenticator, wrappedSaml2SecurityTokenAuthenticator );

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                List<SecurityTokenResolver> resolvers = new List<SecurityTokenResolver>();
                resolvers.Add( saml11SecurityTokenHandler.Configuration.ServiceTokenResolver );
                resolvers.Add( saml2SecurityTokenHandler.Configuration.ServiceTokenResolver );
                outOfBandTokenResolver = new AggregateTokenResolver( resolvers );
            }
            else if ( saml11SecurityTokenHandler == null && saml2SecurityTokenHandler != null )
            {
                //
                // SAML 1.1 token handler is not present but SAML 2.0 is. Set the token type to SAML 2.0
                //

                securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
            }
            else if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler == null )
            {
                //
                // SAML 1.1 token handler is present but SAML 2.0 is not. Set the token type to SAML 1.1
                //

                securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );

                // The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
                outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
            }
            else
            {
                securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
            }

            return securityTokenAuthenticator;
        }

        /// <summary>
        /// Converts the ListenUri in the <see cref="SecurityTokenRequirement"/> to a normalized string.
        /// The method preserves the Uri scheme, port and absolute path and replaces the host name 
        /// with the string 'NormalizedHostName'.
        /// </summary>
        /// <param name="tokenRequirement">The <see cref="SecurityTokenRequirement"/> which contains the 'ListenUri' property.</param>
        /// <returns>A string representing the Normalized URI string.</returns>
        public static string GetNormalizedEndpointId( SecurityTokenRequirement tokenRequirement )
        {
            if ( tokenRequirement == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
            }

            Uri listenUri = null;
            if ( tokenRequirement.Properties.ContainsKey( ListenUriProperty ) )
            {
                listenUri = tokenRequirement.Properties[ListenUriProperty] as Uri;
            }

            if ( listenUri == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4287, tokenRequirement ) );
            }

            if ( listenUri.IsDefaultPort )
            {
                return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName{1}", listenUri.Scheme, listenUri.AbsolutePath );
            }
            else
            {
                return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName:{1}{2}", listenUri.Scheme, listenUri.Port, listenUri.AbsolutePath );
            }
        }
    }

}