/// <summary>
        /// Initializes an instance of <see cref="IdentityConfiguration"/>
        /// </summary>
        public IdentityConfiguration()
        {
            SystemIdentityModelSection   section = SystemIdentityModelSection.Current;
            IdentityConfigurationElement element = (section != null) ? section.IdentityConfigurationElements.GetElement(DefaultServiceName) : null;

            LoadConfiguration(element);
        }
        /// <summary>
        /// Loads the settings for the IdentityConfiguration from the application or web configuration file.
        /// </summary>
        /// <remarks>
        /// If there is no configuration file, or the named section does not exist, then no exception is thrown,
        /// instead the class is loaded with a set of default values.
        /// </remarks>
        protected void LoadConfiguration(IdentityConfigurationElement element)
        {
            if (element != null)
            {
                //
                // Load the claims authentication manager
                //
                if (element.ClaimsAuthenticationManager.IsConfigured)
                {
                    _claimsAuthenticationManager = GetClaimsAuthenticationManager(element);
                }

                //
                // Load the claims authorization manager.
                //
                if (element.ClaimsAuthorizationManager.IsConfigured)
                {
                    _claimsAuthorizationManager = CustomTypeElement.Resolve <ClaimsAuthorizationManager>(element.ClaimsAuthorizationManager);
                }

                //
                // Load the service level Security Token Handler configuration
                //
                _serviceHandlerConfiguration = LoadHandlerConfiguration(element);
            }

            //
            // Reads handler configuration via LoadConfiguredHandlers. Do this last.
            //
            _securityTokenHandlerCollectionManager = LoadHandlers(element);
        }
        protected override void BaseAdd(ConfigurationElement element)
        {
            string name = GetElementKey(element) as string;
            IdentityConfigurationElement result = base.BaseGet(name) as IdentityConfigurationElement;

            if (result != null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7029, "<identityConfiguation>", name));
            }

            base.BaseAdd(element);
        }
 private static ClaimsAuthenticationManager GetClaimsAuthenticationManager(IdentityConfigurationElement element)
 {
     try
     {
         return(CustomTypeElement.Resolve <ClaimsAuthenticationManager>(element.ClaimsAuthenticationManager));
     }
     catch (ArgumentException inner)
     {
         throw DiagnosticUtility.ThrowHelperConfigurationError(
                   element, ConfigurationStrings.ClaimsAuthenticationManager, inner);
     }
 }
 private static SecurityTokenResolver GetIssuerTokenResolver(IdentityConfigurationElement element)
 {
     try
     {
         return(CustomTypeElement.Resolve <SecurityTokenResolver>(element.IssuerTokenResolver));
     }
     catch (ArgumentException inner)
     {
         throw DiagnosticUtility.ThrowHelperConfigurationError(
                   element, ConfigurationStrings.IssuerTokenResolver, inner);
     }
 }
        /// <summary>
        /// Retrieves the ServiceElement with the specified name.
        /// </summary>
        /// <param name="name">The name of the ServiceElement to retrieve</param>
        /// <returns>A ServiceElement instance</returns>
        public IdentityConfigurationElement GetElement(string name)
        {
            if (name == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
            }

            IdentityConfigurationElement result = base.BaseGet(name) as IdentityConfigurationElement;

            if (!StringComparer.Ordinal.Equals(name, ConfigurationStrings.DefaultConfigurationElementName) && result == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7012, name));
            }

            return(result);
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }

            IdentityConfigurationElement elementAsServiceElement = element as IdentityConfigurationElement;

            if (elementAsServiceElement == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7013));
            }

            return(elementAsServiceElement.Name);
        }
        /// <summary>
        /// Initializes an instance of <see cref="IdentityConfiguration"/>
        /// </summary>
        /// <param name="loadConfig">Whether or not config should be loaded.</param>
        /// <exception cref="InvalidOperationException">Thrown if loadConfig is set to true but there is no
        /// &lt;System.IdentityModel> configuration element</exception>
        public IdentityConfiguration(bool loadConfig)
        {
            if (loadConfig)
            {
                SystemIdentityModelSection section = SystemIdentityModelSection.Current;

                if (section == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7027));
                }

                IdentityConfigurationElement element = section.IdentityConfigurationElements.GetElement(DefaultServiceName);
                LoadConfiguration(element);
            }
            else
            {
                LoadConfiguration(null);
            }
        }
        /// <summary>
        /// Initializes an instance of <see cref="IdentityConfiguration"/>
        /// </summary>
        /// <param name="identityConfigurationName">The name of the &lt;service> element from which configuration is to be loaded.</param>
        /// <exception cref="InvalidOperationException">Thrown if there is no &lt;System.IdentityModel> configuration element</exception>
        /// <remarks>If this constructor is called then a System.IdentityModel config section with the provided name must exist.</remarks>
        public IdentityConfiguration(string identityConfigurationName)
        {
            if (identityConfigurationName == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identityConfigurationName");
            }

            SystemIdentityModelSection section = SystemIdentityModelSection.Current;

            if (section == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID7027));
            }

            _identityConfigurationName = identityConfigurationName;
            IdentityConfigurationElement element = section.IdentityConfigurationElements.GetElement(identityConfigurationName);

            LoadConfiguration(element);
        }
        /// <summary>
        /// Loads a SecurityTokenHandlerConfiguration using the elements directly under the ServiceElement.
        /// </summary>
        protected SecurityTokenHandlerConfiguration LoadHandlerConfiguration(IdentityConfigurationElement element)
        {

            SecurityTokenHandlerConfiguration handlerConfiguration = new SecurityTokenHandlerConfiguration();

            try
            {
                if (element.ElementInformation.Properties[ConfigurationStrings.MaximumClockSkew].ValueOrigin != PropertyValueOrigin.Default)
                {
                    handlerConfiguration.MaxClockSkew = element.MaximumClockSkew;
                }
                else
                {
                    handlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;
                }
            }
            catch (ArgumentException inner)
            {
                throw DiagnosticUtility.ThrowHelperConfigurationError(element, ConfigurationStrings.MaximumClockSkew, inner);
            }

            if (element.AudienceUris.IsConfigured)
            {
                handlerConfiguration.AudienceRestriction.AudienceMode = element.AudienceUris.Mode;

                foreach (AudienceUriElement audienceUriElement in element.AudienceUris)
                {
                    handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUriElement.Value, UriKind.RelativeOrAbsolute));
                }
            }
            if (element.Caches.IsConfigured)
            {
                if (element.Caches.TokenReplayCache.IsConfigured)
                {
                    handlerConfiguration.Caches.TokenReplayCache = CustomTypeElement.Resolve<TokenReplayCache>(element.Caches.TokenReplayCache);
                }

                if (element.Caches.SessionSecurityTokenCache.IsConfigured)
                {
                    handlerConfiguration.Caches.SessionSecurityTokenCache = CustomTypeElement.Resolve<SessionSecurityTokenCache>(element.Caches.SessionSecurityTokenCache);
                }
            }

            if (element.CertificateValidation.IsConfigured)
            {
                handlerConfiguration.RevocationMode = element.CertificateValidation.RevocationMode;
                handlerConfiguration.CertificateValidationMode = element.CertificateValidation.CertificateValidationMode;
                handlerConfiguration.TrustedStoreLocation = element.CertificateValidation.TrustedStoreLocation;

                if (element.CertificateValidation.CertificateValidator.IsConfigured)
                {
                    handlerConfiguration.CertificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(element.CertificateValidation.CertificateValidator);
                }
            }

            //
            // Load the issuer name registry
            //
            if (element.IssuerNameRegistry.IsConfigured)
            {
                handlerConfiguration.IssuerNameRegistry = GetIssuerNameRegistry(element.IssuerNameRegistry);
            }

            //
            // Load the issuer token resolver
            //
            if (element.IssuerTokenResolver.IsConfigured)
            {
                handlerConfiguration.IssuerTokenResolver = GetIssuerTokenResolver(element);
            }

            //
            // SaveBootstrapContext
            //
            handlerConfiguration.SaveBootstrapContext = element.SaveBootstrapContext;

            //
            // Load the service token resolver
            //
            if (element.ServiceTokenResolver.IsConfigured)
            {
                handlerConfiguration.ServiceTokenResolver = GetServiceTokenResolver(element);
            }

            //
            // TokenReplayCache related items
            //
            if (element.TokenReplayDetection.IsConfigured)
            {
                //
                // Set on SecurityTokenHandlerConfiguration
                //

                // DetectReplayedTokens set - { true | false }
                //
                handlerConfiguration.DetectReplayedTokens = element.TokenReplayDetection.Enabled;

                // ExpirationPeriod { TimeSpan }
                //
                handlerConfiguration.TokenReplayCacheExpirationPeriod = element.TokenReplayDetection.ExpirationPeriod;
            }

            return handlerConfiguration;
        }
        /// <summary>
        /// Loads the <see cref="SecurityTokenHandlerCollectionManager"/> defined for a given service.
        /// </summary>
        /// <param name="serviceElement">The <see cref="IdentityConfigurationElement"/> used to configure this instance.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerCollectionManager LoadHandlers(IdentityConfigurationElement serviceElement)
        {
            //
            // We start with a token handler collection manager that contains a single collection that includes the default
            // handlers for the system.
            //
            SecurityTokenHandlerCollectionManager manager = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            if (serviceElement != null)
            {
                //
                // Load any token handler collections that appear as part of this service element
                //
                if (serviceElement.SecurityTokenHandlerSets.Count > 0)
                {
                    foreach (SecurityTokenHandlerElementCollection handlerElementCollection in serviceElement.SecurityTokenHandlerSets)
                    {
                        try
                        {
                            SecurityTokenHandlerConfiguration handlerConfiguration;
                            SecurityTokenHandlerCollection handlerCollection;

                            if (string.IsNullOrEmpty(handlerElementCollection.Name) ||
                                 StringComparer.Ordinal.Equals(handlerElementCollection.Name, ConfigurationStrings.DefaultConfigurationElementName))
                            {
                                //
                                // For the default collection, merge the IdentityConfiguration with the underlying config, if it exists.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    //
                                    // Configuration from a nested configuration object. We start with Service level configuration for 
                                    // handlers and then override the collection specific configuration. The result is a new configuration
                                    // object that can only be modified by accessing the collection or handlers configuration properties.
                                    //
                                    _serviceHandlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                    handlerConfiguration = LoadHandlerConfiguration(_serviceHandlerConfiguration, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // No nested configuration object. We use the values from the ServiceElement for this case.
                                    //
                                    handlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                }

                                _serviceHandlerConfiguration = handlerConfiguration;
                            }
                            else
                            {
                                //
                                // This is a non-default collection. There should be no settings inherited from IdentityConfiguration.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    handlerConfiguration = LoadHandlerConfiguration(null, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // If there is no underlying config, set everything as default.
                                    //
                                    handlerConfiguration = new SecurityTokenHandlerConfiguration();
                                }
                            }

                            handlerCollection = new SecurityTokenHandlerCollection(handlerConfiguration);
                            manager[handlerElementCollection.Name] = handlerCollection;

                            foreach (CustomTypeElement handlerElement in handlerElementCollection)
                            {
                                handlerCollection.Add(CustomTypeElement.Resolve<SecurityTokenHandler>(handlerElement));
                            }
                        }
                        catch (ArgumentException inner)
                        {
                            throw DiagnosticUtility.ThrowHelperConfigurationError(serviceElement, handlerElementCollection.Name, inner);
                        }
                    }
                }
                //
                // Ensure that the default usage collection always exists
                //
                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }
            else
            {
                //
                // Ensure that the default usage collection always exists
                //
                _serviceHandlerConfiguration = new SecurityTokenHandlerConfiguration();

                _serviceHandlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;

                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }

            return manager;
        }
        /// <summary>
        /// Loads the settings for the IdentityConfiguration from the application or web configuration file.
        /// </summary>
        /// <remarks>
        /// If there is no configuration file, or the named section does not exist, then no exception is thrown,
        /// instead the class is loaded with a set of default values.
        /// </remarks>
        protected void LoadConfiguration(IdentityConfigurationElement element)
        {

            if (element != null)
            {
                //
                // Load the claims authentication manager
                //
                if (element.ClaimsAuthenticationManager.IsConfigured)
                {
                    _claimsAuthenticationManager = GetClaimsAuthenticationManager(element);
                }

                //
                // Load the claims authorization manager.
                //
                if (element.ClaimsAuthorizationManager.IsConfigured)
                {
                    _claimsAuthorizationManager = CustomTypeElement.Resolve<ClaimsAuthorizationManager>(element.ClaimsAuthorizationManager);
                }

                //
                // Load the service level Security Token Handler configuration
                //
                _serviceHandlerConfiguration = LoadHandlerConfiguration(element);
            }

            //
            // Reads handler configuration via LoadConfiguredHandlers. Do this last.
            //
            _securityTokenHandlerCollectionManager = LoadHandlers(element);
        }
 private static ClaimsAuthenticationManager GetClaimsAuthenticationManager(IdentityConfigurationElement element)
 {
     try
     {
         return CustomTypeElement.Resolve<ClaimsAuthenticationManager>(element.ClaimsAuthenticationManager);
     }
     catch (ArgumentException inner)
     {
         throw DiagnosticUtility.ThrowHelperConfigurationError(
             element, ConfigurationStrings.ClaimsAuthenticationManager, inner);
     }
 }
 private static SecurityTokenResolver GetIssuerTokenResolver(IdentityConfigurationElement element)
 {
     try
     {
         return CustomTypeElement.Resolve<SecurityTokenResolver>(element.IssuerTokenResolver);
     }
     catch (ArgumentException inner)
     {
         throw DiagnosticUtility.ThrowHelperConfigurationError(
             element, ConfigurationStrings.IssuerTokenResolver, inner);
     }
 }
        /// <summary>
        /// Loads a SecurityTokenHandlerConfiguration using the elements directly under the ServiceElement.
        /// </summary>
        protected SecurityTokenHandlerConfiguration LoadHandlerConfiguration(IdentityConfigurationElement element)
        {
            SecurityTokenHandlerConfiguration handlerConfiguration = new SecurityTokenHandlerConfiguration();

            try
            {
                if (element.ElementInformation.Properties[ConfigurationStrings.MaximumClockSkew].ValueOrigin != PropertyValueOrigin.Default)
                {
                    handlerConfiguration.MaxClockSkew = element.MaximumClockSkew;
                }
                else
                {
                    handlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;
                }
            }
            catch (ArgumentException inner)
            {
                throw DiagnosticUtility.ThrowHelperConfigurationError(element, ConfigurationStrings.MaximumClockSkew, inner);
            }

            if (element.AudienceUris.IsConfigured)
            {
                handlerConfiguration.AudienceRestriction.AudienceMode = element.AudienceUris.Mode;

                foreach (AudienceUriElement audienceUriElement in element.AudienceUris)
                {
                    handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUriElement.Value, UriKind.RelativeOrAbsolute));
                }
            }
            if (element.Caches.IsConfigured)
            {
                if (element.Caches.TokenReplayCache.IsConfigured)
                {
                    handlerConfiguration.Caches.TokenReplayCache = CustomTypeElement.Resolve <TokenReplayCache>(element.Caches.TokenReplayCache);
                }

                if (element.Caches.SessionSecurityTokenCache.IsConfigured)
                {
                    handlerConfiguration.Caches.SessionSecurityTokenCache = CustomTypeElement.Resolve <SessionSecurityTokenCache>(element.Caches.SessionSecurityTokenCache);
                }
            }

            if (element.CertificateValidation.IsConfigured)
            {
                handlerConfiguration.RevocationMode            = element.CertificateValidation.RevocationMode;
                handlerConfiguration.CertificateValidationMode = element.CertificateValidation.CertificateValidationMode;
                handlerConfiguration.TrustedStoreLocation      = element.CertificateValidation.TrustedStoreLocation;

                if (element.CertificateValidation.CertificateValidator.IsConfigured)
                {
                    handlerConfiguration.CertificateValidator = CustomTypeElement.Resolve <X509CertificateValidator>(element.CertificateValidation.CertificateValidator);
                }
            }

            //
            // Load the issuer name registry
            //
            if (element.IssuerNameRegistry.IsConfigured)
            {
                handlerConfiguration.IssuerNameRegistry = GetIssuerNameRegistry(element.IssuerNameRegistry);
            }

            //
            // Load the issuer token resolver
            //
            if (element.IssuerTokenResolver.IsConfigured)
            {
                handlerConfiguration.IssuerTokenResolver = GetIssuerTokenResolver(element);
            }

            //
            // SaveBootstrapContext
            //
            handlerConfiguration.SaveBootstrapContext = element.SaveBootstrapContext;

            //
            // Load the service token resolver
            //
            if (element.ServiceTokenResolver.IsConfigured)
            {
                handlerConfiguration.ServiceTokenResolver = GetServiceTokenResolver(element);
            }

            //
            // TokenReplayCache related items
            //
            if (element.TokenReplayDetection.IsConfigured)
            {
                //
                // Set on SecurityTokenHandlerConfiguration
                //

                // DetectReplayedTokens set - { true | false }
                //
                handlerConfiguration.DetectReplayedTokens = element.TokenReplayDetection.Enabled;

                // ExpirationPeriod { TimeSpan }
                //
                handlerConfiguration.TokenReplayCacheExpirationPeriod = element.TokenReplayDetection.ExpirationPeriod;
            }

            return(handlerConfiguration);
        }
        /// <summary>
        /// Loads the <see cref="SecurityTokenHandlerCollectionManager"/> defined for a given service.
        /// </summary>
        /// <param name="serviceElement">The <see cref="IdentityConfigurationElement"/> used to configure this instance.</param>
        /// <returns></returns>
        protected SecurityTokenHandlerCollectionManager LoadHandlers(IdentityConfigurationElement serviceElement)
        {
            //
            // We start with a token handler collection manager that contains a single collection that includes the default
            // handlers for the system.
            //
            SecurityTokenHandlerCollectionManager manager = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            if (serviceElement != null)
            {
                //
                // Load any token handler collections that appear as part of this service element
                //
                if (serviceElement.SecurityTokenHandlerSets.Count > 0)
                {
                    foreach (SecurityTokenHandlerElementCollection handlerElementCollection in serviceElement.SecurityTokenHandlerSets)
                    {
                        try
                        {
                            SecurityTokenHandlerConfiguration handlerConfiguration;
                            SecurityTokenHandlerCollection    handlerCollection;

                            if (string.IsNullOrEmpty(handlerElementCollection.Name) ||
                                StringComparer.Ordinal.Equals(handlerElementCollection.Name, ConfigurationStrings.DefaultConfigurationElementName))
                            {
                                //
                                // For the default collection, merge the IdentityConfiguration with the underlying config, if it exists.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    //
                                    // Configuration from a nested configuration object. We start with Service level configuration for
                                    // handlers and then override the collection specific configuration. The result is a new configuration
                                    // object that can only be modified by accessing the collection or handlers configuration properties.
                                    //
                                    _serviceHandlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                    handlerConfiguration         = LoadHandlerConfiguration(_serviceHandlerConfiguration, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // No nested configuration object. We use the values from the ServiceElement for this case.
                                    //
                                    handlerConfiguration = LoadHandlerConfiguration(serviceElement);
                                }

                                _serviceHandlerConfiguration = handlerConfiguration;
                            }
                            else
                            {
                                //
                                // This is a non-default collection. There should be no settings inherited from IdentityConfiguration.
                                //
                                if (handlerElementCollection.SecurityTokenHandlerConfiguration.IsConfigured)
                                {
                                    handlerConfiguration = LoadHandlerConfiguration(null, handlerElementCollection.SecurityTokenHandlerConfiguration);
                                }
                                else
                                {
                                    //
                                    // If there is no underlying config, set everything as default.
                                    //
                                    handlerConfiguration = new SecurityTokenHandlerConfiguration();
                                }
                            }

                            handlerCollection = new SecurityTokenHandlerCollection(handlerConfiguration);
                            manager[handlerElementCollection.Name] = handlerCollection;

                            foreach (CustomTypeElement handlerElement in handlerElementCollection)
                            {
                                handlerCollection.Add(CustomTypeElement.Resolve <SecurityTokenHandler>(handlerElement));
                            }
                        }
                        catch (ArgumentException inner)
                        {
                            throw DiagnosticUtility.ThrowHelperConfigurationError(serviceElement, handlerElementCollection.Name, inner);
                        }
                    }
                }
                //
                // Ensure that the default usage collection always exists
                //
                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }
            else
            {
                //
                // Ensure that the default usage collection always exists
                //
                _serviceHandlerConfiguration = new SecurityTokenHandlerConfiguration();

                _serviceHandlerConfiguration.MaxClockSkew = _serviceMaxClockSkew;

                if (!manager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.Default))
                {
                    manager[SecurityTokenHandlerCollectionManager.Usage.Default] = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(_serviceHandlerConfiguration);
                }
            }

            return(manager);
        }