< Summary - CoreWCF Coverage — PR #1766

Information
Class: CoreWCF.IdentityModel.Tokens.SessionSecurityToken
Assembly: CoreWCF.Primitives
File(s): /home/runner/work/CoreWCF/CoreWCF/src/CoreWCF.Primitives/src/CoreWCF/IdentityModel/Tokens/SessionSecurityToken.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 631
Coverable lines: 631
Total lines: 1677
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 324
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.cctor()100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)100%110%
.ctor(...)0%220%
.ctor(...)0%32320%
.ctor(...)0%46460%
GetObjectData(...)0%12120%
ReadPrincipal(...)0%16160%
ReadIdentities(...)0%10100%
ReadIdentity(...)0%14140%
GetUpn(...)0%10100%
ReadClaims(...)0%10100%
ReadClaimProperties(...)0%12120%
WritePrincipal(...)0%880%
WriteIdentities(...)0%880%
WriteIdentity(...)0%40400%
WriteClaims(...)0%22220%
WriteClaimProperties(...)0%14140%
SerializeSysClaim(...)0%28280%
DeserializeSysClaim(...)0%28280%
SerializeSid(...)100%110%
ReadRightAttribute(...)0%220%
WriteRightAttribute(...)0%220%
IsPossibleUpn(...)0%880%

File(s)

/home/runner/work/CoreWCF/CoreWCF/src/CoreWCF.Primitives/src/CoreWCF/IdentityModel/Tokens/SessionSecurityToken.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System;
 5using System.Collections.Generic;
 6using System.Collections.ObjectModel;
 7using System.IO;
 8using System.Runtime.Serialization;
 9using System.Runtime.Serialization.Formatters.Binary;
 10using System.Security.Claims;
 11using System.Security.Cryptography;
 12using System.Security.Cryptography.X509Certificates;
 13using System.Security.Principal;
 14using System.Xml;
 15using CoreWCF.IdentityModel.Claims;
 16using CoreWCF.IdentityModel.Policy;
 17using Claim = System.Security.Claims.Claim;
 18using ClaimTypes = System.Security.Claims.ClaimTypes;
 19using SysClaim = CoreWCF.IdentityModel.Claims.Claim;
 20using SysClaimTypes = CoreWCF.IdentityModel.Claims.ClaimTypes;
 21using SysUniqueId = System.Xml.UniqueId;
 22
 23namespace CoreWCF.IdentityModel.Tokens
 24{
 25    /// <summary>
 26    /// Defines a SessionSecurityToken that contains data associated with a session.
 27    /// </summary>
 28    [Serializable]
 29    public class SessionSecurityToken : SecurityToken, ISerializable
 30    {
 31        private const string SupportedVersion = "1";
 32        private const string TokenKey = "SessionToken";
 033        private static readonly Dictionary<string, string> DomainNameMap = new Dictionary<string, string>(MaxDomainNameM
 34        private const int MaxDomainNameMapSize = 50;
 35        private readonly string _context;
 36        private bool _isPersistent;
 37        private readonly ClaimsPrincipal _claimsPrincipal;
 38        private readonly SctAuthorizationPolicy _sctAuthorizationPolicy;
 39        private readonly string _endpointId;
 40        private bool _isReferenceMode;
 41        private readonly bool _isSecurityContextSecurityTokenWrapper;
 42        private readonly string _id;
 43        private readonly SysUniqueId _contextId;
 44        private readonly SysUniqueId _keyGeneration;
 45        private readonly DateTime _keyEffectiveTime;
 46        private readonly DateTime _keyExpirationTime;
 47        private readonly Uri _secureConversationVersion;
 48        private readonly DateTime _validFrom;
 49        private readonly DateTime _validTo;
 50        private readonly ReadOnlyCollection<SecurityKey> _securityKeys;
 51
 52        /// <summary>
 53        /// Create session security token from a principal.
 54        /// </summary>
 55        /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/>.</param>
 56        /// <returns></returns>
 57        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal)
 058            : this(claimsPrincipal, null)
 059        { }
 60
 61        /// <summary>
 62        /// Create session security token from a principal.
 63        /// </summary>
 64        /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/>.</param>
 65        /// <param name="lifetime">The Timespan the token is valid.</param>
 66        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, TimeSpan lifetime)
 067            : this(claimsPrincipal, null, DateTime.UtcNow, DateTimeUtil.AddNonNegative(DateTime.UtcNow, lifetime))
 68        {
 069        }
 70
 71        /// <summary>
 72        /// Create session security token from principal and bootstrap token.
 73        /// </summary>
 74        /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/> that generated from the bootstrap token.</pa
 75        /// <param name="context">Session specific context string</param>
 76        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, string context)
 077            : this(claimsPrincipal, context, DateTime.UtcNow, DateTimeUtil.AddNonNegative(DateTime.UtcNow, SessionSecuri
 078        { }
 79
 80        /// <summary>
 81        /// Create session security token from principal and bootstrap token.
 82        /// </summary>
 83        /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/> that generated from the bootstrap token.</pa
 84        /// <param name="context">Session specific context string</param>
 85        /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param>
 86        /// <param name="validTo">DateTime specifying the time the token becomes invalid.</param>
 87        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, string context, DateTime? validFrom, DateTime? vali
 088            : this(claimsPrincipal, new SysUniqueId(), context, string.Empty, validFrom, validTo, null)
 089        { }
 90
 91        /// <summary>
 92        /// Create session security token from principal and bootstrap token.
 93        /// </summary>
 94        /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/> that generated from the bootstrap token.</pa
 95        /// <param name="context">Session specific context string</param>
 96        /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped tok
 97        /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param>
 98        /// <param name="validTo">DateTime specifying the time the token becomes invalid.</param>
 99        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal, string context, string endpointId, DateTime? validF
 0100            : this(claimsPrincipal, new SysUniqueId(), context, endpointId, validFrom, validTo, null)
 0101        { }
 102
 103        /// <summary>
 104        /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class.
 105        /// </summary>
 106        /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param>
 107        /// <param name="contextId">Optional context identifier associated with this token.  If null a new identifier wi
 108        /// <param name="context">Optional context information associated with the session.</param>
 109        /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped tok
 110        /// <param name="lifetime">The lifetime of the session token.  ValidFrom will be set to DateTime.UtcNow, ValidTo
 111        /// <param name="key">Optional symmetric session key.</param>
 112        /// <exception cref="InvalidOperationException">The value of lifetime &lt;= TimeSpan.Zero."</exception>
 113        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal,
 114                                     SysUniqueId contextId,
 115                                     string context,
 116                                     string endpointId,
 117                                     TimeSpan lifetime,
 118                                     SymmetricSecurityKey key)
 0119            : this(claimsPrincipal, contextId, context, endpointId, DateTime.UtcNow, lifetime, key)
 120        {
 0121        }
 122
 123        /// <summary>
 124        /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class.
 125        /// </summary>
 126        /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param>
 127        /// <param name="contextId">Optional context identifier associated with this token.  If null a new identifier wi
 128        /// <param name="context">Optional context information associated with the session.</param>
 129        /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped tok
 130        /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param>
 131        /// <param name="lifetime">The lifetime of the session token.  ValidTo will be set to ValidFrom + lifetime.</par
 132        /// <param name="key">Optional symmetric session key.</param>
 133        /// <exception cref="InvalidOperationException">The value of lifetime &lt;= TimeSpan.Zero."</exception>
 134        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal,
 135                                     SysUniqueId contextId,
 136                                     string context,
 137                                     string endpointId,
 138                                     DateTime validFrom,
 139                                     TimeSpan lifetime,
 140                                     SymmetricSecurityKey key)
 0141            : this(claimsPrincipal, contextId, context, endpointId, validFrom, DateTimeUtil.AddNonNegative(validFrom, li
 142        {
 0143        }
 144
 145        /// <summary>
 146        /// Initializes a new instance of the <see cref="SessionSecurityToken"/> class.
 147        /// </summary>
 148        /// <param name="claimsPrincipal"><see cref="ClaimsPrincipal"/> associated with this session.</param>
 149        /// <param name="contextId">Context Identifier that identifies the session</param>
 150        /// <param name="context">Optional context information associated with the session.</param>
 151        /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped tok
 152        /// <param name="validFrom">DateTime specifying the time the token becomes valid.</param>
 153        /// <param name="validTo">DateTime specifying the time the token becomes invalid.</param>
 154        /// <param name="key">Optional symmetric session key.</param>
 155        /// <exception cref="ArgumentNullException">The input parameter 'claimsPrincipal' is null.</exception>
 156        /// <exception cref="ArgumentNullException">The input parameter 'contextId' is null.</exception>
 157        /// <exception cref="ArgumentOutOfRangeException">validFrom is greater than or equal to validTo.</exception>
 158        /// <exception cref="ArgumentOutOfRangeException">validTo is less than current time.</exception>
 159        /// <remarks>
 160        /// If no key is supplied, a 128bit key is generated. KeyEffectiveTime is set to validFrom, KeyExpirationTime is
 161        /// A key generation identifier is created.
 162        /// </remarks>
 163        public SessionSecurityToken(ClaimsPrincipal claimsPrincipal,
 164                                     SysUniqueId contextId,
 165                                     string context,
 166                                     string endpointId,
 167                                     DateTime? validFrom,
 168                                     DateTime? validTo,
 169                                     SymmetricSecurityKey key)
 0170            : this(claimsPrincipal, contextId, SecurityUniqueId.Create().Value, context, key?.GetSymmetricKey(), endpoin
 171        {
 0172        }
 173
 174        /// <summary>
 175        /// Core ctor with all parameters in their most primitive form.  This constructor is used in deserialization and
 176        /// when generating a wrapper SessionSecurityToken from a SecurityContextSecurityToken.
 177        /// </summary>
 178        /// <param name="contextId">Context identifier</param>
 179        /// <param name="id">Token identifier</param>
 180        /// <param name="context">Session context data</param>
 181        /// <param name="endpointId">The endpoint to which this token is bound. String.Empty would create a unscoped tok
 182        /// <param name="key">Key material</param>
 183        /// <param name="validFrom">Start time</param>
 184        /// <param name="validTo">End time</param>
 185        /// <param name="keyGeneration">Key Generation identifier</param>
 186        /// <param name="keyEffectiveTime">Key start time</param>
 187        /// <param name="keyExpirationTime">Key end time</param>
 188        /// <param name="authorizationPolicies">Authorization policies</param>
 189        /// <param name="securityContextSecurityTokenWrapperSecureConversationVersion">The version of
 190        /// WS-SecureConversation used to generate this SCT.  This should be null if the token is not an SCT wrapper.</p
 191        internal SessionSecurityToken(ClaimsPrincipal claimsPrincipal,
 192                                       SysUniqueId contextId,
 193                                       string id,
 194                                       string context,
 195                                       byte[] key,
 196                                       string endpointId,
 197                                       DateTime? validFrom,
 198                                       DateTime? validTo,
 199                                       SysUniqueId keyGeneration,
 200                                       DateTime? keyEffectiveTime,
 201                                       DateTime? keyExpirationTime,
 202                                       SctAuthorizationPolicy sctAuthorizationPolicy,
 203                                       Uri securityContextSecurityTokenWrapperSecureConversationVersion)
 0204            : base()
 205        {
 0206            if (claimsPrincipal == null || claimsPrincipal.Identities == null)
 207            {
 0208                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(claimsPrincipal));
 209            }
 210
 0211            if (contextId == null)
 212            {
 0213                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contextId));
 214            }
 215
 216            //
 217            // validFrom and validTo may not have values.
 218            // need to set them to reasonable defaults before moving forward.
 219            // SecurityContextSecurityToken will check the values, but I choose to check
 220            // here to keep the exception in our stack.
 221            //
 222
 223            DateTime validFromEffective;
 224            DateTime validToEffective;
 225
 0226            if (validFrom.HasValue)
 227            {
 0228                validFromEffective = validFrom.Value.ToUniversalTime();
 229            }
 230            else
 231            {
 0232                validFromEffective = DateTime.UtcNow;
 233            }
 234
 0235            if (validTo.HasValue)
 236            {
 0237                validToEffective = validTo.Value.ToUniversalTime();
 238            }
 239            else
 240            {
 0241                validToEffective = validFromEffective.Add(SessionSecurityTokenHandler.DefaultTokenLifetime);
 242            }
 243
 0244            if (validFromEffective >= validToEffective)
 245            {
 0246                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(validFr
 247            }
 248
 0249            if (validToEffective < DateTime.UtcNow)
 250            {
 0251                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(validTo
 252            }
 253
 0254            if (endpointId == null)
 255            {
 0256                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endpointId));
 257            }
 258
 0259            if (!keyEffectiveTime.HasValue)
 260            {
 0261                keyEffectiveTime = (DateTime?)validFromEffective;
 262            }
 263
 0264            if (!keyExpirationTime.HasValue)
 265            {
 0266                keyExpirationTime = (DateTime?)validToEffective;
 267            }
 268
 0269            if (keyEffectiveTime.Value > keyExpirationTime.Value || keyEffectiveTime.Value < validFromEffective)
 270            {
 0271                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(keyEffe
 272            }
 273
 0274            if (keyExpirationTime.Value > validToEffective)
 275            {
 0276                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(keyExpi
 277            }
 278
 0279            if (securityContextSecurityTokenWrapperSecureConversationVersion == null)
 280            {
 281                // Not an SCT wrapper: use the default namespace.
 0282                _secureConversationVersion = WSSecureConversation13Constants.NamespaceUri;
 283            }
 284            else
 285            {
 286                // SCT wrapper: use the provided namespace.
 0287                _isSecurityContextSecurityTokenWrapper = true;
 0288                _secureConversationVersion = securityContextSecurityTokenWrapperSecureConversationVersion;
 289            }
 290
 0291            if (key == null)
 292            {
 293                // We have to create a dummy key here. We are not in WCF and we will
 294                // never use this key. But this is created only to satisfy WCF's
 295                // SecurityContextSecurityToken constructor.
 0296                key = CryptoHelper.GenerateSymmetricKey(128);
 297            }
 298
 0299            if (endpointId == null)
 300            {
 0301                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endpointId));
 302            }
 303
 0304            _claimsPrincipal = claimsPrincipal;
 0305            _contextId = contextId;
 0306            _id = id;
 0307            _context = context;
 0308            _securityKeys = new ReadOnlyCollection<SecurityKey>(new SecurityKey[] { new InMemorySymmetricSecurityKey(key
 0309            _endpointId = endpointId;
 0310            _validFrom = validFrom.Value;
 0311            _validTo = validTo.Value;
 0312            _keyGeneration = keyGeneration;
 0313            _keyEffectiveTime = keyEffectiveTime.Value;
 0314            _keyExpirationTime = keyExpirationTime.Value;
 0315            _sctAuthorizationPolicy = sctAuthorizationPolicy;
 0316        }
 317
 0318        protected SessionSecurityToken(SerializationInfo info, StreamingContext context)
 319        {
 0320            if (info == null)
 0321                return;
 322
 0323            byte[] cookie = (byte[])info.GetValue(TokenKey, typeof(byte[]));
 324
 0325            if (null == cookie || 0 == cookie.Length)
 326            {
 0327                throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation(SR.Format(SR.ID4272));
 328            }
 329
 0330            SessionDictionary dictionary = SessionDictionary.Instance;
 331            //
 332            // We are creating a reader over the decrypted form of the cookie that is in memory.
 333            // Passing Max for the XmlDictionaryReaderQuotas is safe.
 334            //
 0335            using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(cookie, 0, cookie.Length, diction
 336            {
 337                //
 338                // Layout is strict, must be in following order:
 339                //
 340                // Version
 341                // SecureConversationVersion
 342                // ID
 343                // ContextID
 344                // Key
 345                // Generation {optional}
 346                // EffectiveTime
 347                // ExpiryTime
 348                // KeyEffectiveTime
 349                // KeyExpiryTime
 350                //
 351                // SessionSecurityToken data may follow, in the order:
 352                //
 0353                bool isSecurityContextSecurityTokenWrapper = false;
 0354                bool isPersistent = true;
 0355                bool isReferenceMode = false;
 0356                string cookieContext = string.Empty;
 357
 0358                if (reader.IsStartElement(dictionary.SecurityContextToken, dictionary.EmptyString))
 359                {
 0360                    isSecurityContextSecurityTokenWrapper = true;
 361                }
 0362                else if (reader.IsStartElement(dictionary.SessionToken, dictionary.EmptyString))
 363                {
 364                    //@PersistentTrue
 0365                    if (reader.GetAttribute(dictionary.PersistentTrue, dictionary.EmptyString) == null)
 366                    {
 0367                        isPersistent = false;
 368                    }
 369
 0370                    if (reader.GetAttribute(dictionary.ReferenceModeTrue, dictionary.EmptyString) != null)
 371                    {
 0372                        isReferenceMode = true;
 373                    }
 374
 0375                    reader.ReadFullStartElement();
 0376                    reader.MoveToContent();
 377
 378                    // <Context>
 0379                    if (reader.IsStartElement(dictionary.Context, dictionary.EmptyString))
 380                    {
 0381                        cookieContext = reader.ReadElementContentAsString();
 382                    }
 383                }
 384                else
 385                {
 0386                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 387                }
 388
 0389                string version = reader.ReadElementString();
 0390                if (version != SupportedVersion)
 391                {
 0392                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 393                }
 394
 395                //
 396                // SecureConversation Version
 397                //
 0398                string scNamespace = reader.ReadElementString();
 399                Uri scVersion;
 400
 0401                if (scNamespace == WSSecureConversationFeb2005Constants.Namespace)
 402                {
 0403                    scVersion = WSSecureConversationFeb2005Constants.NamespaceUri;
 404                }
 0405                else if (scNamespace == WSSecureConversation13Constants.Namespace)
 406                {
 0407                    scVersion = WSSecureConversation13Constants.NamespaceUri;
 408                }
 409                else
 410                {
 0411                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 412                }
 413
 0414                string instanceIdentifier = null;
 0415                if (reader.IsStartElement(dictionary.Id, dictionary.EmptyString))
 416                {
 0417                    instanceIdentifier = reader.ReadElementString();
 418                }
 419
 0420                if (string.IsNullOrEmpty(instanceIdentifier))
 421                {
 0422                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR
 423                }
 424
 0425                if (!reader.IsStartElement(dictionary.ContextId, dictionary.EmptyString))
 426                {
 0427                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 428                }
 429
 0430                SysUniqueId contextIdentifier = reader.ReadElementContentAsUniqueId();
 431
 0432                if (!reader.IsStartElement(dictionary.Key, dictionary.EmptyString))
 433                {
 0434                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 435                }
 0436                byte[] key = reader.ReadElementContentAsBase64();
 437
 438                // optional
 0439                SysUniqueId generation = null;
 0440                if (reader.IsStartElement(dictionary.KeyGeneration, dictionary.EmptyString))
 441                {
 0442                    generation = reader.ReadElementContentAsUniqueId();
 443                }
 444
 0445                if (!reader.IsStartElement(dictionary.EffectiveTime, dictionary.EmptyString))
 446                {
 0447                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 448                }
 0449                DateTime effectiveTime = new DateTime(XmlUtil.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
 450
 0451                if (!reader.IsStartElement(dictionary.ExpiryTime, dictionary.EmptyString))
 452                {
 0453                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 454                }
 0455                DateTime expiryTime = new DateTime(XmlUtil.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
 456
 0457                if (!reader.IsStartElement(dictionary.KeyEffectiveTime, dictionary.EmptyString))
 458                {
 0459                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 460                }
 0461                DateTime keyEffectiveTime = new DateTime(XmlUtil.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
 462
 0463                if (!reader.IsStartElement(dictionary.KeyExpiryTime, dictionary.EmptyString))
 464                {
 0465                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 466                }
 0467                DateTime keyExpiryTime = new DateTime(XmlUtil.ReadElementContentAsInt64(reader), DateTimeKind.Utc);
 468
 0469                ClaimsPrincipal principal = null;
 470
 0471                if (reader.IsStartElement(dictionary.ClaimsPrincipal, dictionary.EmptyString))
 472                {
 0473                    principal = ReadPrincipal(reader, dictionary);
 474                }
 475
 0476                SctAuthorizationPolicy sctAuthorizationPolicy = null;
 0477                if (reader.IsStartElement(dictionary.SctAuthorizationPolicy, dictionary.EmptyString))
 478                {
 0479                    reader.ReadStartElement(dictionary.SctAuthorizationPolicy, dictionary.EmptyString);
 0480                    SysClaim sysClaim = DeserializeSysClaim(reader);
 0481                    reader.ReadEndElement();
 0482                    sctAuthorizationPolicy = new SctAuthorizationPolicy(sysClaim);
 483                }
 484
 0485                string endpointId = null;
 0486                if (reader.IsStartElement(dictionary.EndpointId, dictionary.EmptyString))
 487                {
 0488                    endpointId = reader.ReadElementContentAsString();
 489                }
 490
 0491                reader.ReadEndElement();
 492
 0493                _claimsPrincipal = principal;
 0494                _contextId = contextIdentifier;
 0495                _id = instanceIdentifier;
 0496                _context = cookieContext;
 0497                _securityKeys = new ReadOnlyCollection<SecurityKey>(new SecurityKey[] { new InMemorySymmetricSecurityKey
 0498                _endpointId = endpointId;
 0499                _validFrom = effectiveTime;
 0500                _validTo = expiryTime;
 0501                _keyGeneration = generation;
 0502                _keyEffectiveTime = keyEffectiveTime;
 0503                _keyExpirationTime = keyExpiryTime;
 0504                _isSecurityContextSecurityTokenWrapper = isSecurityContextSecurityTokenWrapper;
 0505                _secureConversationVersion = scVersion;
 0506                _sctAuthorizationPolicy = sctAuthorizationPolicy;
 0507                _isPersistent = isPersistent;
 0508                _isReferenceMode = isReferenceMode;
 509
 0510            }
 0511        }
 512
 513        /// <summary>
 514        /// The <see cref="ClaimsPrincipal"/> associated with the session.
 515        /// </summary>
 0516        public ClaimsPrincipal ClaimsPrincipal => _claimsPrincipal;
 517
 518        /// <summary>
 519        /// Gets the user specified value.
 520        /// </summary>
 0521        public string Context => _context;
 522
 523        /// <summary>
 524        /// The Session Context Identifier
 525        /// </summary>
 0526        public SysUniqueId ContextId => _contextId;
 527
 528        /// <summary>
 529        /// Gets the Id of the endpoint to which this token is scoped.
 530        /// </summary>
 0531        public string EndpointId => _endpointId;
 532
 533        /// <summary>
 534        /// Gets a value indicating whether this token is wrapping an SCT.
 535        /// </summary>
 0536        internal bool IsSecurityContextSecurityTokenWrapper => _isSecurityContextSecurityTokenWrapper;
 537
 538        /// <summary>
 539        /// The effective date/time of the key in this token
 540        /// </summary>
 0541        public DateTime KeyEffectiveTime => _keyEffectiveTime;
 542
 543        /// <summary>
 544        /// The expiration date/time of the key in this token
 545        /// </summary>
 0546        public DateTime KeyExpirationTime => _keyExpirationTime;
 547
 548        /// <summary>
 549        /// The identifier for the key generation in this token
 550        /// </summary>
 0551        public SysUniqueId KeyGeneration => _keyGeneration;
 552
 553        /// <summary>
 554        /// Gets the id of this token.
 555        /// </summary>
 0556        public override string Id => _id;
 557
 558        /// <summary>
 559        /// If true, cookie is written as a persistent cookie.
 560        /// </summary>
 561        public bool IsPersistent
 562        {
 0563            get { return _isPersistent; }
 0564            set { _isPersistent = value; }
 565        }
 566
 567        /// <summary>
 568        /// If true, the SessionSecurityToken is operating in reference mode.
 569        /// </summary>
 570        /// <remarks>
 571        /// In reference mode, a simple artifact is produced during serialization
 572        /// and the real token is stored in the token cache associated with the
 573        /// token handler. For Web Farm scenarios, the token cache must operate
 574        /// across all nodes in teh farm.
 575        /// </remarks>
 576        public bool IsReferenceMode
 577        {
 578            get
 579            {
 0580                return _isReferenceMode;
 581            }
 582            set
 583            {
 0584                _isReferenceMode = value;
 0585            }
 586        }
 587
 588        /// <summary>
 589        /// Gets the authorization policies associated with the session. Only has meaning if this is wrapping an SCT
 590        /// token.
 591        /// </summary>
 0592        internal SctAuthorizationPolicy SctAuthorizationPolicy => _sctAuthorizationPolicy;
 593
 594        /// <summary>
 595        /// Gets the SecureConversationVersion used for this token.
 596        /// </summary>
 0597        public Uri SecureConversationVersion => _secureConversationVersion;
 598
 599        /// <summary>
 600        /// Gets the keys associated with this session, usually a single key
 601        /// </summary>
 0602        public override ReadOnlyCollection<SecurityKey> SecurityKeys => _securityKeys;
 603
 604        /// <summary>
 605        /// Gets the begining DateTime before which token is invalid.
 606        /// </summary>
 0607        public override DateTime ValidFrom => _validFrom;
 608
 609        /// <summary>
 610        /// Gets the ending DateTime after which the token is invalid.
 611        /// </summary>
 0612        public override DateTime ValidTo => _validTo;
 613
 614        #region ISerializable Members
 615
 616        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
 617        {
 0618            MemoryStream stream = new MemoryStream();
 0619            SessionDictionary dictionary = SessionDictionary.Instance;
 620
 621            //
 622            // XmlDictionaryWriter.CreateBinaryWriter() defaults to ownsStream=true.
 623            // So, the XmlWriter returned by the below code owns the memory stream, and will dispose it.
 624            //
 0625            using (XmlDictionaryWriter dicWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary))
 626            {
 627                //<SecurityContextSecurityToken> or <SessionSecurityToken>
 0628                if (IsSecurityContextSecurityTokenWrapper)
 629                {
 0630                    dicWriter.WriteStartElement(dictionary.SecurityContextToken, dictionary.EmptyString);
 631                }
 632                else
 633                {
 0634                    dicWriter.WriteStartElement(dictionary.SessionToken, dictionary.EmptyString);
 635
 636                    // @PersistentTrue
 0637                    if (IsPersistent)
 638                    {
 0639                        dicWriter.WriteAttributeString(dictionary.PersistentTrue, dictionary.EmptyString, "");
 640                    }
 641
 642                    // @ReferenceModeTrue
 0643                    if (IsReferenceMode)
 644                    {
 0645                        dicWriter.WriteAttributeString(dictionary.ReferenceModeTrue, dictionary.EmptyString, "");
 646                    }
 647
 648                    // <Context>
 0649                    if (!string.IsNullOrEmpty(Context))
 650                    {
 0651                        dicWriter.WriteElementString(dictionary.Context, dictionary.EmptyString, Context);
 652                    }
 653                }
 654
 655                // Serialization Format Version
 656                // <Version>1</Version>
 0657                dicWriter.WriteStartElement(dictionary.Version, dictionary.EmptyString);
 0658                dicWriter.WriteValue(SupportedVersion);
 0659                dicWriter.WriteEndElement();
 660
 661                //
 662                // SecureConversation Version
 663                //
 0664                dicWriter.WriteElementString(dictionary.SecureConversationVersion, dictionary.EmptyString, SecureConvers
 665
 666                //
 667                // ID and ContextId
 668                //
 0669                dicWriter.WriteElementString(dictionary.Id, dictionary.EmptyString, Id);
 0670                XmlUtil.WriteElementStringAsUniqueId(dicWriter, dictionary.ContextId, dictionary.EmptyString, ContextId.
 671
 672                //
 673                // Key material
 674                //
 0675                byte[] key = ((SymmetricSecurityKey)SecurityKeys[0]).GetSymmetricKey();
 676
 0677                dicWriter.WriteStartElement(dictionary.Key, dictionary.EmptyString);
 0678                dicWriter.WriteBase64(key, 0, key.Length);
 0679                dicWriter.WriteEndElement();
 680
 681                //
 682                // Key Generation
 683                //
 0684                if (KeyGeneration != null)
 685                {
 0686                    XmlUtil.WriteElementStringAsUniqueId(dicWriter, dictionary.KeyGeneration, dictionary.EmptyString, Ke
 687                }
 688
 689                //
 690                // Effective and Expiry dates
 691                //
 0692                XmlUtil.WriteElementContentAsInt64(dicWriter, dictionary.EffectiveTime, dictionary.EmptyString, ValidFro
 0693                XmlUtil.WriteElementContentAsInt64(dicWriter, dictionary.ExpiryTime, dictionary.EmptyString, ValidTo.ToU
 0694                XmlUtil.WriteElementContentAsInt64(dicWriter, dictionary.KeyEffectiveTime, dictionary.EmptyString, KeyEf
 0695                XmlUtil.WriteElementContentAsInt64(dicWriter, dictionary.KeyExpiryTime, dictionary.EmptyString, KeyExpir
 696
 697                //
 698                // Claims Principal
 699                //
 0700                WritePrincipal(dicWriter, dictionary, ClaimsPrincipal);
 701
 702                // The WCF SCT will have a SctAuthorizationPolicy that wraps the Primary Identity
 703                // of the bootstrap token. This is required for SCT renewal scenarios. Write the
 704                // SctAuthorizationPolicy if one is available.
 0705                if (SctAuthorizationPolicy != null)
 706                {
 0707                    dicWriter.WriteStartElement(dictionary.SctAuthorizationPolicy, dictionary.EmptyString);
 0708                    SysClaim identityClaim = ((CoreWCF.IdentityModel.Claims.DefaultClaimSet)((IAuthorizationPolicy)SctAu
 0709                    SerializeSysClaim(identityClaim, dicWriter);
 0710                    dicWriter.WriteEndElement();
 711                }
 712
 0713                dicWriter.WriteElementString(dictionary.EndpointId, dictionary.EmptyString, EndpointId);
 0714                dicWriter.WriteEndElement();
 0715                dicWriter.Flush();
 716
 0717                info.AddValue(TokenKey, stream.ToArray());
 0718            }
 0719        }
 720
 721        #endregion
 722
 723        /// <summary>
 724        /// Reads a ClaimsPrincipal from a XmlDictionaryReader.
 725        /// </summary>
 726        /// <param name=nameof(dictionaryReader)>XmlDictionaryReader positioned at dictionary.ClaimsPrincipal.</param>
 727        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 728        /// <exception cref="ArgumentNullException">The input argument 'dictionaryReader' or 'dictionary' is null.</exce
 729        /// <returns>ClaimsPrincipal</returns>
 730        private ClaimsPrincipal ReadPrincipal(XmlDictionaryReader dictionaryReader, SessionDictionary dictionary)
 731        {
 0732            if (dictionaryReader == null)
 733            {
 0734                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryReader));
 735            }
 736
 0737            if (dictionary == null)
 738            {
 0739                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 740            }
 741
 0742            ClaimsPrincipal principal = null;
 743
 0744            Collection<ClaimsIdentity> identities = new Collection<ClaimsIdentity>();
 745
 0746            dictionaryReader.MoveToContent();
 747
 0748            if (dictionaryReader.IsStartElement(dictionary.ClaimsPrincipal, dictionary.EmptyString))
 749            {
 0750                dictionaryReader.ReadFullStartElement();
 751
 0752                ReadIdentities(dictionaryReader, dictionary, identities);
 753
 0754                dictionaryReader.ReadEndElement();
 755            }
 756
 757            // If we find a WindowsIdentity in the identities we just read, we should be creating a WindowsPrincipal usi
 0758            WindowsIdentity wi = null;
 0759            foreach (ClaimsIdentity identity in identities)
 760            {
 0761                wi = identity as WindowsIdentity;
 0762                if (wi != null)
 763                {
 0764                    principal = new WindowsPrincipal(wi);
 0765                    break;
 766                }
 767            }
 768
 769            // If we did create a WindowsPrincipal we can remove the associated WindowsIdentity from the identities coll
 770            // so that we dont add it twice in the subsequent step
 0771            if (principal != null)
 772            {
 0773                identities.Remove(wi);
 774            }
 0775            else if (identities.Count > 0)
 776            {
 777                // If we did not create a WindowsPrincipal, default to a ClaimsPrincipal
 0778                principal = new ClaimsPrincipal();
 779            }
 780
 0781            if (principal != null)
 782            {
 783                // Add the identities we just read to the principal
 0784                principal.AddIdentities(identities);
 785            }
 786
 0787            return principal;
 788        }
 789
 790        /// <summary>
 791        /// Reads the ClaimsIdentites from a XmlDictionaryReader and adds them to a ClaimIdentityColleciton.
 792        /// </summary>
 793        /// <param name=nameof(dictionaryReader)>XmlDictionaryReader positioned at dictionary.Identities</param>
 794        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 795        /// <param name=nameof(identities)>A collection of <see cref="ClaimsIdentity"/> to populate.</param>
 796        /// <exception cref="ArgumentNullException">The input argument 'dictionaryReader', 'dictionary' or 'identities' 
 797        /// <remarks>Reads 'n' identies and adds them to identies.</remarks>
 798        private void ReadIdentities(XmlDictionaryReader dictionaryReader, SessionDictionary dictionary, Collection<Claim
 799        {
 0800            if (dictionaryReader == null)
 801            {
 0802                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryReader));
 803            }
 804
 0805            if (dictionary == null)
 806            {
 0807                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 808            }
 809
 0810            if (identities == null)
 811            {
 0812                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(identities));
 813            }
 814
 0815            dictionaryReader.MoveToContent();
 816
 0817            if (dictionaryReader.IsStartElement(dictionary.Identities, dictionary.EmptyString))
 818            {
 0819                dictionaryReader.ReadFullStartElement();
 820
 0821                while (dictionaryReader.IsStartElement(dictionary.Identity, dictionary.EmptyString))
 822                {
 0823                    identities.Add(ReadIdentity(dictionaryReader, dictionary));
 824                }
 825
 0826                dictionaryReader.ReadEndElement();
 827            }
 0828        }
 829
 830        /// <summary>
 831        /// Reads a single ClaimsIdentity from a XmlDictionaryReader.
 832        /// </summary>
 833        /// <param name=nameof(dictionaryReader)>XmlDictionaryReader positioned at dictionary.Identity.</param>
 834        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 835        /// <exception cref="ArgumentNullException">The input argument 'dictionaryReader' or 'dictionary' is null.</exce
 836        /// <exception cref="SecurityTokenException">The dictionaryReader is not positioned a SessionDictionary.Identity
 837        /// <returns>ClaimsIdentity</returns>
 838        private ClaimsIdentity ReadIdentity(XmlDictionaryReader dictionaryReader, SessionDictionary dictionary)
 839        {
 0840            if (dictionaryReader == null)
 841            {
 0842                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryReader));
 843            }
 844
 0845            if (dictionary == null)
 846            {
 0847                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 848            }
 849
 0850            dictionaryReader.MoveToContent();
 851
 0852            ClaimsIdentity identity = null;
 853
 0854            if (!dictionaryReader.IsStartElement(dictionary.Identity, dictionary.EmptyString))
 855            {
 0856                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID3007
 857            }
 858
 859            // @NameClaimType
 0860            string nameClaimType = dictionaryReader.GetAttribute(dictionary.NameClaimType, dictionary.EmptyString);
 861
 862            // @RoleClaimType
 0863            string roleClaimType = dictionaryReader.GetAttribute(dictionary.RoleClaimType, dictionary.EmptyString);
 864
 865            // @WindowsLogonName (optional) => windows claims identity
 0866            string logonName = dictionaryReader.GetAttribute(dictionary.WindowsLogonName, dictionary.EmptyString);
 0867            string authenticationType = dictionaryReader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyStr
 868
 0869            if (string.IsNullOrEmpty(logonName))
 870            {
 0871                identity = new ClaimsIdentity(authenticationType, nameClaimType, roleClaimType);
 872            }
 873            else
 874            {
 875                // The WindowsIdentity(string, string) c'tor does not set the Auth type. Hence we use that c'tor to get 
 876                // call the other c'tor that actually sets the authType passed in.
 877                // DevDiv 279196 tracks the issue and in WindowsIdentity c'tor. Its too late to fix it in 4.5 cycle as w
 878                // able to complete the analysis of the change for the current release. This should be investigated in 5
 0879                WindowsIdentity winId = new WindowsIdentity(GetUpn(logonName));
 0880                identity = new WindowsIdentity(winId.Token, authenticationType);
 881            }
 882
 883            // @Label
 0884            identity.Label = dictionaryReader.GetAttribute(dictionary.Label, dictionary.EmptyString);
 885
 886
 0887            dictionaryReader.ReadFullStartElement();
 888
 889            // <ClaimCollection>
 0890            if (dictionaryReader.IsStartElement(dictionary.ClaimCollection, dictionary.EmptyString))
 891            {
 0892                dictionaryReader.ReadStartElement();
 893
 0894                Collection<Claim> claims = new Collection<Claim>();
 0895                ReadClaims(dictionaryReader, dictionary, claims);
 0896                identity.AddClaims(claims);
 897
 0898                dictionaryReader.ReadEndElement();
 899            }
 900
 901            // <Actor>
 0902            if (dictionaryReader.IsStartElement(dictionary.Actor, dictionary.EmptyString))
 903            {
 0904                dictionaryReader.ReadStartElement();
 905
 0906                identity.Actor = ReadIdentity(dictionaryReader, dictionary);
 907
 0908                dictionaryReader.ReadEndElement();
 909            }
 910
 0911            if (dictionaryReader.IsStartElement(dictionary.BootstrapToken, dictionary.EmptyString))
 912            {
 0913                dictionaryReader.ReadStartElement();
 914
 0915                byte[] bytes = dictionaryReader.ReadContentAsBase64();
 0916                using (MemoryStream ms = new MemoryStream(bytes))
 917                {
 0918                    BinaryFormatter formatter = new BinaryFormatter();
 0919                    identity.BootstrapContext = (BootstrapContext)formatter.Deserialize(ms);
 0920                }
 921
 0922                dictionaryReader.ReadEndElement();
 923            }
 924
 0925            dictionaryReader.ReadEndElement(); // Identity
 926
 0927            return identity;
 928        }
 929
 930        /// <summary>
 931        /// Returns a User Principal Name from a windows logon name.
 932        /// </summary>
 933        /// <param name="windowsLogonName">Name to translate into the UPN</param>
 934        /// <exception cref="ArgumentNullException">The input argument 'windowsLogonName' is null or empty.</exception>
 935        /// <exception cref="InvalidOperationException">If 'windowsLogonName' is not of the form domain\\user or user@do
 936        /// <returns>A User Principal Name of the form 'user@domain'</returns>
 937        private string GetUpn(string windowsLogonName)
 938        {
 0939            if (string.IsNullOrEmpty(windowsLogonName))
 940            {
 0941                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(windowsLogonName));
 942            }
 0943            int delimiterPos = windowsLogonName.IndexOf('\\');
 944
 0945            if ((delimiterPos < 0) || (delimiterPos == 0) || (delimiterPos == windowsLogonName.Length - 1))
 946            {
 0947                if (IsPossibleUpn(windowsLogonName))
 948                {
 0949                    return windowsLogonName;
 950                }
 951
 0952                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ID4
 953            }
 954
 0955            string shortDomainName = windowsLogonName.Substring(0, delimiterPos + 1);
 0956            string userName = windowsLogonName.Substring(delimiterPos + 1);
 957            string fullDomainName;
 958            bool found;
 959
 960            // 1) Read from cache
 0961            lock (DomainNameMap)
 962            {
 0963                found = DomainNameMap.TryGetValue(shortDomainName, out fullDomainName);
 0964            }
 965
 0966            return userName + "@" + fullDomainName;
 967        }
 968
 969        /// <summary>
 970        /// Reads Claims from a XmlDictionaryReader and adds them to a ClaimCollection.
 971        /// </summary>
 972        /// <param name=nameof(dictionaryReader)>XmlDictionaryReader positioned at dictionary.Claim.</param>
 973        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 974        /// <param name="claims">ClaimCollection to add the claims to.</param>
 975        /// <exception cref="ArgumentNullException">The input argument 'dictionaryReader',  'dictionary' or 'claims' is 
 976        /// <remarks>Reads 'n' claims and adds them to claims.</remarks>
 977        private void ReadClaims(XmlDictionaryReader dictionaryReader, SessionDictionary dictionary, Collection<Claim> cl
 978        {
 0979            if (dictionaryReader == null)
 980            {
 0981                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryReader));
 982            }
 983
 0984            if (dictionary == null)
 985            {
 0986                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 987            }
 988
 0989            if (claims == null)
 990            {
 0991                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claims");
 992            }
 993
 0994            while (dictionaryReader.IsStartElement(dictionary.Claim, dictionary.EmptyString))
 995            {
 996                // @Issuer (optional), @OriginalIssuer (optional), @Type, @Value, @ValueType
 997
 0998                Claim claim = new Claim(dictionaryReader.GetAttribute(dictionary.Type, dictionary.EmptyString),
 0999                                         dictionaryReader.GetAttribute(dictionary.Value, dictionary.EmptyString),
 01000                                         dictionaryReader.GetAttribute(dictionary.ValueType, dictionary.EmptyString),
 01001                                         dictionaryReader.GetAttribute(dictionary.Issuer, dictionary.EmptyString),
 01002                                         dictionaryReader.GetAttribute(dictionary.OriginalIssuer, dictionary.EmptyString
 1003
 01004                dictionaryReader.ReadFullStartElement();
 1005
 1006                // <Properties> (optional)
 01007                if (dictionaryReader.IsStartElement(dictionary.ClaimProperties, dictionary.EmptyString))
 1008                {
 01009                    ReadClaimProperties(dictionaryReader, dictionary, claim.Properties);
 1010                }
 1011
 01012                dictionaryReader.ReadEndElement();
 1013
 01014                claims.Add(claim);
 1015            }
 01016        }
 1017
 1018        /// <summary>
 1019        /// Reads ClaimProperties from a XmlDictionaryReader and adds them to a Dictionary.
 1020        /// </summary>
 1021        /// <param name=nameof(dictionaryReader)>XmlDictionaryReader positioned at the element dictionary.ClaimPropertie
 1022        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1023        /// <param name=nameof(properties)>Dictionary to add properties to.</param>
 1024        /// <exception cref="ArgumentNullException">The input argument 'dictionaryReader',  'dictionary' or 'properties'
 1025        /// <exception cref="SecurityTokenException">Is thrown if the 'name' of a property is null or an empty string.</
 1026        /// <exception cref="SecurityTokenException">Is thrown if the 'value' of a property is null.</exception>
 1027        /// <remarks>Reads 'n' properties.</remarks>
 1028        private void ReadClaimProperties(XmlDictionaryReader dictionaryReader, SessionDictionary dictionary, IDictionary
 1029        {
 01030            if (dictionaryReader == null)
 1031            {
 01032                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryReader));
 1033            }
 1034
 01035            if (dictionary == null)
 1036            {
 01037                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1038            }
 1039
 01040            if (properties == null)
 1041            {
 01042                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(properties));
 1043            }
 1044
 01045            dictionaryReader.ReadStartElement();
 1046
 1047            // <Property>
 01048            while (dictionaryReader.IsStartElement(dictionary.ClaimProperty, dictionary.EmptyString))
 1049            {
 1050                // @Name, @Value
 1051
 01052                string name = dictionaryReader.GetAttribute(dictionary.ClaimPropertyName, dictionary.EmptyString);
 01053                string value = dictionaryReader.GetAttribute(dictionary.ClaimPropertyValue, dictionary.EmptyString);
 1054
 01055                if (string.IsNullOrEmpty(name))
 1056                {
 01057                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 1058                }
 1059
 01060                if (string.IsNullOrEmpty(value))
 1061                {
 01062                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID
 1063                }
 1064
 01065                properties.Add(new KeyValuePair<string, string>(name, value));
 1066
 01067                dictionaryReader.ReadFullStartElement();
 01068                dictionaryReader.ReadEndElement();
 1069            }
 1070
 01071            dictionaryReader.ReadEndElement();
 01072        }
 1073
 1074        /// <summary>
 1075        /// Writes out a ClaimsPrincipal using a XmlDictionaryWriter.
 1076        /// </summary>
 1077        /// <param name="dictionaryWriter">XmlDictionaryWriter to write to.</param>
 1078        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1079        /// <param name="principal">ClaimsPrincipal to write.</param>
 1080        /// <exception cref="ArgumentNullException">The input argument 'dictionaryWriter', 'dictionary' or 'principal' i
 1081        private void WritePrincipal(XmlDictionaryWriter dictionaryWriter, SessionDictionary dictionary, ClaimsPrincipal 
 1082        {
 01083            if (dictionaryWriter == null)
 1084            {
 01085                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryWriter));
 1086            }
 1087
 01088            if (dictionary == null)
 1089            {
 01090                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1091            }
 1092
 01093            if (principal == null)
 1094            {
 01095                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(principal));
 1096            }
 1097
 1098            // <ClaimsPrincipal>
 01099            dictionaryWriter.WriteStartElement(dictionary.ClaimsPrincipal, dictionary.EmptyString);
 1100
 01101            if (principal.Identities != null)
 1102            {
 01103                WriteIdentities(dictionaryWriter, dictionary, principal.Identities);
 1104            }
 1105
 01106            dictionaryWriter.WriteEndElement();
 01107        }
 1108
 1109        /// <summary>
 1110        /// Writes a collection of ClaimsIdentity using a XmlDictionaryWriter.
 1111        /// </summary>
 1112        /// <param name="dictionaryWriter">XmlDictionaryWriter to write to.</param>
 1113        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1114        /// <param name=nameof(identities)>The collection of ClaimsIdentity to write.</param>
 1115        /// <exception cref="ArgumentNullException">The input argument 'dictionaryWriter', 'dictionary' or 'identities' 
 1116        private void WriteIdentities(XmlDictionaryWriter dictionaryWriter, SessionDictionary dictionary, IEnumerable<Cla
 1117        {
 01118            if (dictionaryWriter == null)
 1119            {
 01120                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryWriter));
 1121            }
 1122
 01123            if (dictionary == null)
 1124            {
 01125                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1126            }
 1127
 01128            if (identities == null)
 1129            {
 01130                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(identities));
 1131            }
 1132
 1133            // <Identities>
 01134            dictionaryWriter.WriteStartElement(dictionary.Identities, dictionary.EmptyString);
 1135
 01136            foreach (ClaimsIdentity ci in identities)
 1137            {
 01138                WriteIdentity(dictionaryWriter, dictionary, ci);
 1139            }
 1140
 01141            dictionaryWriter.WriteEndElement();
 01142        }
 1143
 1144        /// <summary>
 1145        /// Writes a single ClaimsIdentity using a XmlDictionaryWriter.
 1146        /// </summary>
 1147        /// <param name="dictionaryWriter">XmlDictionaryWriter to write to.</param>
 1148        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1149        /// <param name="identity">ClaimsIdentiy to write.</param>
 1150        /// <exception cref="ArgumentNullException">The input argument 'dictionaryWriter', 'dictionary' or 'identity' is
 1151        private void WriteIdentity(XmlDictionaryWriter dictionaryWriter, SessionDictionary dictionary, ClaimsIdentity id
 1152        {
 01153            if (dictionaryWriter == null)
 1154            {
 01155                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryWriter));
 1156            }
 1157
 01158            if (dictionary == null)
 1159            {
 01160                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1161            }
 1162
 01163            if (identity == null)
 1164            {
 01165                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(identity));
 1166            }
 1167
 1168            //
 1169            // WindowsIdentity needs special handling
 1170            //
 1171
 1172            // <Identity>
 01173            dictionaryWriter.WriteStartElement(dictionary.Identity, dictionary.EmptyString);
 1174
 01175            WindowsIdentity wci = identity as WindowsIdentity;
 01176            if (wci != null)
 1177            {
 1178                // @WindowsLogonName (optional)
 01179                dictionaryWriter.WriteAttributeString(dictionary.WindowsLogonName, dictionary.EmptyString, wci.Name);
 1180            }
 1181
 1182            // @AuthenticationType (optional)
 01183            if (!string.IsNullOrEmpty(identity.AuthenticationType))
 1184            {
 01185                dictionaryWriter.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, identity.Au
 1186            }
 1187
 1188            // @LabelWrite (optional)
 01189            if (!string.IsNullOrEmpty(identity.Label))
 1190            {
 01191                dictionaryWriter.WriteAttributeString(dictionary.Label, dictionary.EmptyString, identity.Label);
 1192            }
 1193
 1194            // @NameClaimType (optional)
 01195            if (identity.NameClaimType != null)
 1196            {
 01197                dictionaryWriter.WriteAttributeString(dictionary.NameClaimType, dictionary.EmptyString, identity.NameCla
 1198            }
 1199
 1200            // @RoleClaimType (optional)
 01201            if (identity.RoleClaimType != null)
 1202            {
 01203                dictionaryWriter.WriteAttributeString(dictionary.RoleClaimType, dictionary.EmptyString, identity.RoleCla
 1204            }
 1205
 1206            // <ClaimCollection> (optional)
 01207            if (identity.Claims != null)
 1208            {
 01209                dictionaryWriter.WriteStartElement(dictionary.ClaimCollection, dictionary.EmptyString);
 1210
 01211                WriteClaims(dictionaryWriter, dictionary, identity.Claims, (wci == null) ?
 01212                    (OutboundClaimsFilter)null
 01213                    :
 01214                    // do not serialize SID claims for WindowsIdentities as they will be created when the
 01215                    // windows identity is recreated.
 01216                    delegate(Claim c)
 01217                    {
 01218                        if (c.Type == ClaimTypes.GroupSid
 01219                          || c.Type == ClaimTypes.PrimaryGroupSid
 01220                          || c.Type == ClaimTypes.PrimarySid
 01221                          || c.Type == ClaimTypes.DenyOnlyPrimaryGroupSid
 01222                          || c.Type == ClaimTypes.DenyOnlyPrimarySid
 01223                          || c.Type == ClaimTypes.Name && c.Issuer == ClaimsIdentity.DefaultIssuer && c.ValueType == Cla
 01224                        {
 01225                            return true;
 01226                        }
 01227
 01228                        return false;
 01229                    }
 01230                );
 1231
 01232                dictionaryWriter.WriteEndElement();
 1233            }
 1234
 1235            // <Actor> (optional)
 01236            if (identity.Actor != null)
 1237            {
 01238                dictionaryWriter.WriteStartElement(dictionary.Actor, dictionary.EmptyString);
 1239
 01240                WriteIdentity(dictionaryWriter, dictionary, identity.Actor);
 1241
 01242                dictionaryWriter.WriteEndElement();
 1243            }
 1244
 01245            if (identity.BootstrapContext != null)
 1246            {
 01247                dictionaryWriter.WriteStartElement(dictionary.BootstrapToken, dictionary.EmptyString);
 1248
 01249                using (MemoryStream ms = new MemoryStream())
 1250                {
 01251                    BinaryFormatter formatter = new BinaryFormatter();
 01252                    formatter.Serialize(ms, identity.BootstrapContext);
 01253                    byte[] bootstrapArray = ms.ToArray();
 01254                    dictionaryWriter.WriteBase64(bootstrapArray, 0, bootstrapArray.Length);
 01255                }
 1256
 01257                dictionaryWriter.WriteEndElement(); // </BootstrapToken>
 1258            }
 1259
 01260            dictionaryWriter.WriteEndElement();
 1261
 01262        }
 1263
 1264        /// <summary>
 1265        /// Actor that returns true if a claim should be filtered.
 1266        /// </summary>
 1267        /// <param name="claim">Claim to check.</param>
 1268        /// <returns></returns>
 1269        private delegate bool OutboundClaimsFilter(Claim claim);
 1270
 1271        /// <summary>
 1272        /// Writes a collection of claims using a XmlDictionaryWriter.
 1273        /// </summary>
 1274        /// <param name="dictionaryWriter">XmlDictionaryWriter to write to.</param>
 1275        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1276        /// <param name="claims">ClaimCollection to write.</param>
 1277        /// <param name="outboundClaimsFilter">Filter to apply when writing claims. If parameter is not null and filter 
 1278        /// <exception cref="ArgumentNullException">The input argument 'dictionaryWriter', 'dictionary' or 'claims' is n
 1279        private void WriteClaims(XmlDictionaryWriter dictionaryWriter, SessionDictionary dictionary, IEnumerable<Claim> 
 1280        {
 01281            if (dictionaryWriter == null)
 1282            {
 01283                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryWriter));
 1284            }
 1285
 01286            if (dictionary == null)
 1287            {
 01288                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1289            }
 1290
 01291            if (claims == null)
 1292            {
 01293                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claims");
 1294            }
 1295
 01296            foreach (Claim claim in claims)
 1297            {
 01298                if (claim == null)
 1299                {
 1300                    continue;
 1301                }
 1302
 01303                if (outboundClaimsFilter != null && outboundClaimsFilter(claim))
 1304                {
 1305                    continue;
 1306                }
 1307
 1308                // <Claim>
 01309                dictionaryWriter.WriteStartElement(dictionary.Claim, dictionary.EmptyString);
 1310
 1311                // @Issuer
 01312                if (!string.IsNullOrEmpty(claim.Issuer))
 1313                {
 01314                    dictionaryWriter.WriteAttributeString(dictionary.Issuer, dictionary.EmptyString, claim.Issuer);
 1315                }
 1316
 1317                // @OriginalIssuer
 01318                if (!string.IsNullOrEmpty(claim.OriginalIssuer))
 1319                {
 01320                    dictionaryWriter.WriteAttributeString(dictionary.OriginalIssuer, dictionary.EmptyString, claim.Origi
 1321                }
 1322
 1323                // @Type
 01324                dictionaryWriter.WriteAttributeString(dictionary.Type, dictionary.EmptyString, claim.Type);
 1325
 1326                // @Value
 01327                dictionaryWriter.WriteAttributeString(dictionary.Value, dictionary.EmptyString, claim.Value);
 1328
 1329                // @ValueType
 01330                dictionaryWriter.WriteAttributeString(dictionary.ValueType, dictionary.EmptyString, claim.ValueType);
 1331
 1332                // <Properties>
 01333                if (claim.Properties != null && claim.Properties.Count > 0)
 1334                {
 01335                    WriteClaimProperties(dictionaryWriter, dictionary, claim.Properties);
 1336                }
 1337
 01338                dictionaryWriter.WriteEndElement();
 1339            }
 01340        }
 1341
 1342        /// <summary>
 1343        /// Writes a collection of ClaimProperties using a XmlDictionaryWriter.
 1344        /// </summary>
 1345        /// <param name="dictionaryWriter">XmlDictionaryWriter to write to.</param>
 1346        /// <param name=nameof(dictionary)>SessionDictionary to provide dictionary strings.</param>
 1347        /// <param name=nameof(properties)>ClaimProperties to write.</param>
 1348        /// <exception cref="ArgumentNullException">The input argument 'dictionaryWriter', 'dictionary' or 'properties' 
 1349        private void WriteClaimProperties(XmlDictionaryWriter dictionaryWriter, SessionDictionary dictionary, IDictionar
 1350        {
 01351            if (dictionaryWriter == null)
 1352            {
 01353                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionaryWriter));
 1354            }
 1355
 01356            if (dictionary == null)
 1357            {
 01358                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(dictionary));
 1359            }
 1360
 01361            if (properties == null)
 1362            {
 01363                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(properties));
 1364            }
 1365
 01366            if (properties.Count > 0)
 1367            {
 01368                dictionaryWriter.WriteStartElement(dictionary.ClaimProperties, dictionary.EmptyString);
 1369
 01370                foreach (KeyValuePair<string, string> property in properties)
 1371                {
 1372                    // <ClaimProperty>
 01373                    if (!string.IsNullOrEmpty(property.Key) && !string.IsNullOrEmpty(property.Value))
 1374                    {
 01375                        dictionaryWriter.WriteStartElement(dictionary.ClaimProperty, dictionary.EmptyString);
 1376                        // @Name
 1377
 01378                        dictionaryWriter.WriteAttributeString(dictionary.ClaimPropertyName, dictionary.EmptyString, prop
 1379
 1380                        // @Value
 01381                        dictionaryWriter.WriteAttributeString(dictionary.ClaimPropertyValue, dictionary.EmptyString, pro
 1382
 01383                        dictionaryWriter.WriteEndElement();
 1384                    }
 1385                }
 1386
 01387                dictionaryWriter.WriteEndElement();
 1388            }
 01389        }
 1390
 1391        /// <summary>
 1392        /// Serializes the given <see cref="CoreWCF.IdentityModel.Claims.Claim"/> to the given XmlDictionaryWriter.
 1393        /// </summary>
 1394        /// <param name="claim">The claim to be serialized.</param>
 1395        /// <param name="writer">The XmlDictionaryWriter to which to serialize the claim.</param>
 1396        private void SerializeSysClaim(SysClaim claim, XmlDictionaryWriter writer)
 1397        {
 01398            SessionDictionary dictionary = SessionDictionary.Instance;
 1399
 1400            // the order in which known claim types are checked is optimized for use patterns
 01401            if (claim == null)
 1402            {
 01403                writer.WriteElementString(dictionary.NullValue, dictionary.EmptyString, string.Empty);
 01404                return;
 1405            }
 01406            else if (SysClaimTypes.Sid.Equals(claim.ClaimType))
 1407            {
 01408                writer.WriteStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString);
 01409                WriteRightAttribute(claim, dictionary, writer);
 01410                SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer);
 01411                writer.WriteEndElement();
 01412                return;
 1413            }
 01414            else if (SysClaimTypes.DenyOnlySid.Equals(claim.ClaimType))
 1415            {
 01416                writer.WriteStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString);
 01417                WriteRightAttribute(claim, dictionary, writer);
 01418                SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer);
 01419                writer.WriteEndElement();
 01420                return;
 1421            }
 01422            else if (SysClaimTypes.X500DistinguishedName.Equals(claim.ClaimType))
 1423            {
 01424                writer.WriteStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString);
 01425                WriteRightAttribute(claim, dictionary, writer);
 01426                byte[] rawData = ((X500DistinguishedName)claim.Resource).RawData;
 01427                writer.WriteBase64(rawData, 0, rawData.Length);
 01428                writer.WriteEndElement();
 01429                return;
 1430            }
 01431            else if (SysClaimTypes.Thumbprint.Equals(claim.ClaimType))
 1432            {
 01433                writer.WriteStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString);
 01434                WriteRightAttribute(claim, dictionary, writer);
 01435                byte[] thumbprint = (byte[])claim.Resource;
 01436                writer.WriteBase64(thumbprint, 0, thumbprint.Length);
 01437                writer.WriteEndElement();
 01438                return;
 1439            }
 01440            else if (SysClaimTypes.Name.Equals(claim.ClaimType))
 1441            {
 01442                writer.WriteStartElement(dictionary.NameClaim, dictionary.EmptyString);
 01443                WriteRightAttribute(claim, dictionary, writer);
 01444                writer.WriteString((string)claim.Resource);
 01445                writer.WriteEndElement();
 01446                return;
 1447            }
 01448            else if (SysClaimTypes.Dns.Equals(claim.ClaimType))
 1449            {
 01450                writer.WriteStartElement(dictionary.DnsClaim, dictionary.EmptyString);
 01451                WriteRightAttribute(claim, dictionary, writer);
 01452                writer.WriteString((string)claim.Resource);
 01453                writer.WriteEndElement();
 01454                return;
 1455            }
 01456            else if (SysClaimTypes.Rsa.Equals(claim.ClaimType))
 1457            {
 01458                writer.WriteStartElement(dictionary.RsaClaim, dictionary.EmptyString);
 01459                WriteRightAttribute(claim, dictionary, writer);
 01460                writer.WriteString(((RSA)claim.Resource).ToXmlString(false));
 01461                writer.WriteEndElement();
 01462                return;
 1463            }
 01464            else if (SysClaimTypes.Email.Equals(claim.ClaimType))
 1465            {
 01466                writer.WriteStartElement(dictionary.MailAddressClaim, dictionary.EmptyString);
 01467                WriteRightAttribute(claim, dictionary, writer);
 01468                writer.WriteString(((System.Net.Mail.MailAddress)claim.Resource).Address);
 01469                writer.WriteEndElement();
 01470                return;
 1471            }
 01472            else if (claim == SysClaim.System)
 1473            {
 01474                writer.WriteElementString(dictionary.SystemClaim, dictionary.EmptyString, string.Empty);
 01475                return;
 1476            }
 01477            else if (SysClaimTypes.Hash.Equals(claim.ClaimType))
 1478            {
 01479                writer.WriteStartElement(dictionary.HashClaim, dictionary.EmptyString);
 01480                WriteRightAttribute(claim, dictionary, writer);
 01481                byte[] hash = (byte[])claim.Resource;
 01482                writer.WriteBase64(hash, 0, hash.Length);
 01483                writer.WriteEndElement();
 01484                return;
 1485            }
 01486            else if (SysClaimTypes.Spn.Equals(claim.ClaimType))
 1487            {
 01488                writer.WriteStartElement(dictionary.SpnClaim, dictionary.EmptyString);
 01489                WriteRightAttribute(claim, dictionary, writer);
 01490                writer.WriteString((string)claim.Resource);
 01491                writer.WriteEndElement();
 01492                return;
 1493            }
 01494            else if (SysClaimTypes.Upn.Equals(claim.ClaimType))
 1495            {
 01496                writer.WriteStartElement(dictionary.UpnClaim, dictionary.EmptyString);
 01497                WriteRightAttribute(claim, dictionary, writer);
 01498                writer.WriteString((string)claim.Resource);
 01499                writer.WriteEndElement();
 01500                return;
 1501            }
 01502            else if (SysClaimTypes.Uri.Equals(claim.ClaimType))
 1503            {
 01504                writer.WriteStartElement(dictionary.UrlClaim, dictionary.EmptyString);
 01505                WriteRightAttribute(claim, dictionary, writer);
 01506                writer.WriteString(((Uri)claim.Resource).AbsoluteUri);
 01507                writer.WriteEndElement();
 01508                return;
 1509            }
 1510            else
 1511            {
 01512                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID4290
 1513            }
 1514        }
 1515
 1516        /// <summary>
 1517        /// Deserializes a WCF claim.
 1518        /// </summary>
 1519        /// <param name="reader">XmlReader to the WCF Claim.</param>
 1520        /// <returns>Instance of <see cref="CoreWCF.IdentityModel.Claims.Claim"/></returns>
 1521        private SysClaim DeserializeSysClaim(XmlDictionaryReader reader)
 1522        {
 01523            SessionDictionary dictionary = SessionDictionary.Instance;
 1524
 01525            if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString))
 1526            {
 01527                reader.ReadElementString();
 01528                return null;
 1529            }
 01530            else if (reader.IsStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString))
 1531            {
 01532                string right = ReadRightAttribute(reader, dictionary);
 01533                reader.ReadStartElement();
 01534                byte[] sidBytes = reader.ReadContentAsBase64();
 01535                reader.ReadEndElement();
 01536                return new SysClaim(SysClaimTypes.Sid, new SecurityIdentifier(sidBytes, 0), right);
 1537            }
 01538            else if (reader.IsStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString))
 1539            {
 01540                string right = ReadRightAttribute(reader, dictionary);
 01541                reader.ReadStartElement();
 01542                byte[] sidBytes = reader.ReadContentAsBase64();
 01543                reader.ReadEndElement();
 01544                return new SysClaim(SysClaimTypes.DenyOnlySid, new SecurityIdentifier(sidBytes, 0), right);
 1545            }
 01546            else if (reader.IsStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString))
 1547            {
 01548                string right = ReadRightAttribute(reader, dictionary);
 01549                reader.ReadStartElement();
 01550                byte[] rawData = reader.ReadContentAsBase64();
 01551                reader.ReadEndElement();
 01552                return new SysClaim(SysClaimTypes.X500DistinguishedName, new X500DistinguishedName(rawData), right);
 1553            }
 01554            else if (reader.IsStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString))
 1555            {
 01556                string right = ReadRightAttribute(reader, dictionary);
 01557                reader.ReadStartElement();
 01558                byte[] thumbprint = reader.ReadContentAsBase64();
 01559                reader.ReadEndElement();
 01560                return new SysClaim(SysClaimTypes.Thumbprint, thumbprint, right);
 1561            }
 01562            else if (reader.IsStartElement(dictionary.NameClaim, dictionary.EmptyString))
 1563            {
 01564                string right = ReadRightAttribute(reader, dictionary);
 01565                reader.ReadStartElement();
 01566                string name = reader.ReadString();
 01567                reader.ReadEndElement();
 01568                return new SysClaim(SysClaimTypes.Name, name, right);
 1569            }
 01570            else if (reader.IsStartElement(dictionary.DnsClaim, dictionary.EmptyString))
 1571            {
 01572                string right = ReadRightAttribute(reader, dictionary);
 01573                reader.ReadStartElement();
 01574                string dns = reader.ReadString();
 01575                reader.ReadEndElement();
 01576                return new SysClaim(SysClaimTypes.Dns, dns, right);
 1577            }
 01578            else if (reader.IsStartElement(dictionary.RsaClaim, dictionary.EmptyString))
 1579            {
 01580                string right = ReadRightAttribute(reader, dictionary);
 01581                reader.ReadStartElement();
 01582                string rsaXml = reader.ReadString();
 01583                reader.ReadEndElement();
 1584
 01585                RSA rsa = RSA.Create();
 01586                rsa.FromXmlString(rsaXml);
 01587                return new SysClaim(SysClaimTypes.Rsa, rsa, right);
 1588            }
 01589            else if (reader.IsStartElement(dictionary.MailAddressClaim, dictionary.EmptyString))
 1590            {
 01591                string right = ReadRightAttribute(reader, dictionary);
 01592                reader.ReadStartElement();
 01593                string address = reader.ReadString();
 01594                reader.ReadEndElement();
 01595                return new SysClaim(SysClaimTypes.Email, new System.Net.Mail.MailAddress(address), right);
 1596            }
 01597            else if (reader.IsStartElement(dictionary.SystemClaim, dictionary.EmptyString))
 1598            {
 01599                reader.ReadElementString();
 01600                return SysClaim.System;
 1601            }
 01602            else if (reader.IsStartElement(dictionary.HashClaim, dictionary.EmptyString))
 1603            {
 01604                string right = ReadRightAttribute(reader, dictionary);
 01605                reader.ReadStartElement();
 01606                byte[] hash = reader.ReadContentAsBase64();
 01607                reader.ReadEndElement();
 01608                return new SysClaim(SysClaimTypes.Hash, hash, right);
 1609            }
 01610            else if (reader.IsStartElement(dictionary.SpnClaim, dictionary.EmptyString))
 1611            {
 01612                string right = ReadRightAttribute(reader, dictionary);
 01613                reader.ReadStartElement();
 01614                string spn = reader.ReadString();
 01615                reader.ReadEndElement();
 01616                return new SysClaim(SysClaimTypes.Spn, spn, right);
 1617            }
 01618            else if (reader.IsStartElement(dictionary.UpnClaim, dictionary.EmptyString))
 1619            {
 01620                string right = ReadRightAttribute(reader, dictionary);
 01621                reader.ReadStartElement();
 01622                string upn = reader.ReadString();
 01623                reader.ReadEndElement();
 01624                return new SysClaim(SysClaimTypes.Upn, upn, right);
 1625            }
 01626            else if (reader.IsStartElement(dictionary.UrlClaim, dictionary.EmptyString))
 1627            {
 01628                string right = ReadRightAttribute(reader, dictionary);
 01629                reader.ReadStartElement();
 01630                string url = reader.ReadString();
 01631                reader.ReadEndElement();
 01632                return new SysClaim(SysClaimTypes.Uri, new Uri(url), right);
 1633            }
 1634            else
 1635            {
 01636                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.ID4289
 1637            }
 1638        }
 1639
 1640        private static void SerializeSid(SecurityIdentifier sid, SessionDictionary dictionary, XmlDictionaryWriter write
 1641        {
 01642            byte[] sidBytes = new byte[sid.BinaryLength];
 01643            sid.GetBinaryForm(sidBytes, 0);
 01644            writer.WriteBase64(sidBytes, 0, sidBytes.Length);
 01645        }
 1646
 1647        private static string ReadRightAttribute(XmlDictionaryReader reader, SessionDictionary dictionary)
 1648        {
 01649            string right = reader.GetAttribute(dictionary.Right, dictionary.EmptyString);
 01650            return string.IsNullOrEmpty(right) ? CoreWCF.IdentityModel.Claims.Rights.PossessProperty : right;
 1651        }
 1652
 1653        private static void WriteRightAttribute(SysClaim claim, SessionDictionary dictionary, XmlDictionaryWriter writer
 1654        {
 01655            if (CoreWCF.IdentityModel.Claims.Rights.PossessProperty.Equals(claim.Right))
 01656                return;
 01657            writer.WriteAttributeString(dictionary.Right, dictionary.EmptyString, claim.Right);
 01658        }
 1659
 1660        // As name says, certainly not a complete test, but it will allow us to move forward on
 1661        // strings that are possible UPN's
 1662        // a@b will succeed
 1663        // @a, a@, @ will fail
 1664        private static bool IsPossibleUpn(string name)
 1665        {
 01666            int delimiterPos = name.IndexOf('@');
 1667
 1668            // if it is the first of last character
 01669            if ((name.Length < 3) || (delimiterPos < 0) || (delimiterPos == 0) || (delimiterPos == name.Length - 1))
 1670            {
 01671                return false;
 1672            }
 1673
 01674            return true;
 1675        }
 1676    }
 1677}

Methods/Properties

.cctor()
.ctor(System.Security.Claims.ClaimsPrincipal)
.ctor(System.Security.Claims.ClaimsPrincipal,System.TimeSpan)
.ctor(System.Security.Claims.ClaimsPrincipal,System.String)
.ctor(System.Security.Claims.ClaimsPrincipal,System.String,System.Nullable`1<System.DateTime>,System.Nullable`1<System.DateTime>)
.ctor(System.Security.Claims.ClaimsPrincipal,System.String,System.String,System.Nullable`1<System.DateTime>,System.Nullable`1<System.DateTime>)
.ctor(System.Security.Claims.ClaimsPrincipal,System.Xml.UniqueId,System.String,System.String,System.TimeSpan,CoreWCF.IdentityModel.Tokens.SymmetricSecurityKey)
.ctor(System.Security.Claims.ClaimsPrincipal,System.Xml.UniqueId,System.String,System.String,System.DateTime,System.TimeSpan,CoreWCF.IdentityModel.Tokens.SymmetricSecurityKey)
.ctor(System.Security.Claims.ClaimsPrincipal,System.Xml.UniqueId,System.String,System.String,System.Nullable`1<System.DateTime>,System.Nullable`1<System.DateTime>,CoreWCF.IdentityModel.Tokens.SymmetricSecurityKey)
.ctor(System.Security.Claims.ClaimsPrincipal,System.Xml.UniqueId,System.String,System.String,System.Byte[],System.String,System.Nullable`1<System.DateTime>,System.Nullable`1<System.DateTime>,System.Xml.UniqueId,System.Nullable`1<System.DateTime>,System.Nullable`1<System.DateTime>,CoreWCF.IdentityModel.Tokens.SctAuthorizationPolicy,System.Uri)
.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
ClaimsPrincipal()
Context()
ContextId()
EndpointId()
IsSecurityContextSecurityTokenWrapper()
KeyEffectiveTime()
KeyExpirationTime()
KeyGeneration()
Id()
IsPersistent()
IsPersistent(System.Boolean)
IsReferenceMode()
IsReferenceMode(System.Boolean)
SctAuthorizationPolicy()
SecureConversationVersion()
SecurityKeys()
ValidFrom()
ValidTo()
GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
ReadPrincipal(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary)
ReadIdentities(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.ObjectModel.Collection`1<System.Security.Claims.ClaimsIdentity>)
ReadIdentity(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary)
GetUpn(System.String)
ReadClaims(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.ObjectModel.Collection`1<System.Security.Claims.Claim>)
ReadClaimProperties(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.Generic.IDictionary`2<System.String,System.String>)
WritePrincipal(System.Xml.XmlDictionaryWriter,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Security.Claims.ClaimsPrincipal)
WriteIdentities(System.Xml.XmlDictionaryWriter,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.Generic.IEnumerable`1<System.Security.Claims.ClaimsIdentity>)
WriteIdentity(System.Xml.XmlDictionaryWriter,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Security.Claims.ClaimsIdentity)
WriteClaims(System.Xml.XmlDictionaryWriter,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.Generic.IEnumerable`1<System.Security.Claims.Claim>,CoreWCF.IdentityModel.Tokens.SessionSecurityToken/OutboundClaimsFilter)
WriteClaimProperties(System.Xml.XmlDictionaryWriter,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Collections.Generic.IDictionary`2<System.String,System.String>)
SerializeSysClaim(CoreWCF.IdentityModel.Claims.Claim,System.Xml.XmlDictionaryWriter)
DeserializeSysClaim(System.Xml.XmlDictionaryReader)
SerializeSid(System.Security.Principal.SecurityIdentifier,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Xml.XmlDictionaryWriter)
ReadRightAttribute(System.Xml.XmlDictionaryReader,CoreWCF.IdentityModel.Claims.SessionDictionary)
WriteRightAttribute(CoreWCF.IdentityModel.Claims.Claim,CoreWCF.IdentityModel.Claims.SessionDictionary,System.Xml.XmlDictionaryWriter)
IsPossibleUpn(System.String)