/// <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); } }
public static T Resolve <T>(CustomTypeElement customTypeElement) where T : class { return(TypeResolveHelper.Resolve <T>(customTypeElement, customTypeElement.Type)); }
public JwtSecurityTokenRequirement(XmlElement element) { if (element == null) { throw new ArgumentNullException("element"); } if (element.LocalName != Elements.JwtSecurityTokenRequirement) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10601, element.LocalName, element.OuterXml)); } X509RevocationMode revocationMode = this.defaultRevocationMode; X509CertificateValidationMode certificateValidationMode = this.defaultValidationMode; StoreLocation trustedStoreLocation = this.defaultStoreLocation; string customValidator = null; bool createCertificateValidator = false; HashSet<string> itemsProcessed = new HashSet<string>(); foreach (XmlAttribute attribute in element.Attributes) { if (string.IsNullOrWhiteSpace(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, attribute.LocalName, element.OuterXml)); } if (itemsProcessed.Contains(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10617, attribute.LocalName, element.OuterXml)); } if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.Validator)) { customValidator = attribute.Value; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.RevocationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeNoCheck)) { revocationMode = X509RevocationMode.NoCheck; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOffline)) { revocationMode = X509RevocationMode.Offline; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOnline)) { revocationMode = X509RevocationMode.Online; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.RevocationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}'", AttributeValues.X509RevocationModeNoCheck, AttributeValues.X509RevocationModeOffline, AttributeValues.X509RevocationModeOnline), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.ValidationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeChainTrust)) { certificateValidationMode = X509CertificateValidationMode.ChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerOrChainTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeNone)) { certificateValidationMode = X509CertificateValidationMode.None; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeCustom)) { certificateValidationMode = X509CertificateValidationMode.Custom; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.ValidationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}', '{3}', '{4}'", AttributeValues.X509CertificateValidationModeChainTrust, AttributeValues.X509CertificateValidationModePeerOrChainTrust, AttributeValues.X509CertificateValidationModePeerTrust, AttributeValues.X509CertificateValidationModeNone, AttributeValues.X509CertificateValidationModeCustom), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.TrustedStoreLocation)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationCurrentUser)) { trustedStoreLocation = StoreLocation.CurrentUser; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationLocalMachine)) { trustedStoreLocation = StoreLocation.LocalMachine; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.TrustedStoreLocation, attribute.Value, "'" + AttributeValues.X509TrustedStoreLocationCurrentUser + "', '" + AttributeValues.X509TrustedStoreLocationLocalMachine + "'", element.OuterXml)); } } else { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10608, Elements.JwtSecurityTokenRequirement, attribute.LocalName, element.OuterXml)); } } List<XmlElement> configElements = XmlUtil.GetXmlElements(element.ChildNodes); HashSet<string> elementsProcessed = new HashSet<string>(); foreach (XmlElement childElement in configElements) { if (childElement.Attributes.Count > 1) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10609, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (childElement.Attributes.Count == 0) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10607, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (string.IsNullOrWhiteSpace(childElement.Attributes[0].LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, Attributes.Value, element.OuterXml)); } if (!StringComparer.Ordinal.Equals(childElement.Attributes[0].LocalName, Attributes.Value)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10610, childElement.LocalName, Attributes.Value, childElement.Attributes[0].LocalName, element.OuterXml)); } if (elementsProcessed.Contains(childElement.LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10616, childElement.LocalName, element.OuterXml)); } elementsProcessed.Add(childElement.LocalName); if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.NameClaimType)) { this.NameClaimType = childElement.Attributes[0].Value; } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.RoleClaimType)) { this.RoleClaimType = childElement.Attributes[0].Value; } else { try { if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxTokenSizeInBytes)) { this.MaximumTokenSizeInBytes = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.DefaultTokenLifetimeInMinutes)) { this.DefaultTokenLifetimeInMinutes = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxClockSkewInMinutes)) { this.ClockSkewInSeconds = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10611, Elements.JwtSecurityTokenRequirement, childElement.LocalName, string.Format( CultureInfo.InvariantCulture, "{0}', '{1}', '{2}', '{3}', '{4}", Elements.NameClaimType, Elements.RoleClaimType, Elements.MaxTokenSizeInBytes, Elements.MaxClockSkewInMinutes, Elements.DefaultTokenLifetimeInMinutes), element.OuterXml)); } } catch (OverflowException oex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, oex), oex); } catch (FormatException fex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, fex), fex); } catch (ArgumentOutOfRangeException aex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, aex), aex); } } } if (certificateValidationMode == X509CertificateValidationMode.Custom) { Type customValidatorType = null; if (customValidator == null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10612, Attributes.ValidationMode, Attributes.Validator, element.OuterXml)); } try { customValidatorType = Type.GetType(customValidator, true); CustomTypeElement typeElement = new CustomTypeElement(); typeElement.Type = customValidatorType; this.certificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(typeElement); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10613, customValidator, Attributes.Validator, ex, element.OuterXml), ex); } } else if (customValidator != null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10619, Attributes.Validator, Attributes.ValidationMode, AttributeValues.X509CertificateValidationModeCustom, certificateValidationMode, typeof(X509CertificateValidator).ToString(), customValidator, element.OuterXml)); } else if (createCertificateValidator) { this.certificateValidator = new X509CertificateValidatorEx(certificateValidationMode, revocationMode, trustedStoreLocation); } }
/// <summary> /// Loads configuration elements pertaining to the <see cref="SecurityTokenHandlerCollection"/> /// </summary> /// <param name="baseConfiguration">Base <see cref="SecurityTokenHandlerConfiguration"/> from which to inherit default values.</param> /// <param name="element">The <see cref="SecurityTokenHandlerConfigurationElement"/> from the configuration file.</param> /// <returns></returns> protected SecurityTokenHandlerConfiguration LoadHandlerConfiguration(SecurityTokenHandlerConfiguration baseConfiguration, SecurityTokenHandlerConfigurationElement element) { SecurityTokenHandlerConfiguration handlerConfiguration = (baseConfiguration == null) ? new SecurityTokenHandlerConfiguration() : baseConfiguration; if (element.AudienceUris.IsConfigured) { // // There is no inheritance of the content of the element from base to child, only the whole element. If the // user specifies any part, they must specify it all. // handlerConfiguration.AudienceRestriction.AudienceMode = AudienceUriMode.Always; handlerConfiguration.AudienceRestriction.AllowedAudienceUris.Clear(); 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 = CustomTypeElement.Resolve <SecurityTokenResolver>(element.IssuerTokenResolver); } // // Load MaxClockSkew // try { if (element.ElementInformation.Properties[ConfigurationStrings.MaximumClockSkew].ValueOrigin != PropertyValueOrigin.Default) { handlerConfiguration.MaxClockSkew = element.MaximumClockSkew; } } catch (ArgumentException inner) { throw DiagnosticUtility.ThrowHelperConfigurationError(element, ConfigurationStrings.MaximumClockSkew, inner); } // // SaveBootstrapTokens // if (element.ElementInformation.Properties[ConfigurationStrings.SaveBootstrapContext].ValueOrigin != PropertyValueOrigin.Default) { handlerConfiguration.SaveBootstrapContext = element.SaveBootstrapContext; } // // Load the service token resolver // if (element.ServiceTokenResolver.IsConfigured) { handlerConfiguration.ServiceTokenResolver = CustomTypeElement.Resolve <SecurityTokenResolver>(element.ServiceTokenResolver); } // // 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 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); }