/// <summary>
    /// Returns the collection of certificates that the STS uses to sign tokens.
    /// </summary>
    /// <returns>The collection of certificates.</returns>
    private IEnumerable <X509Certificate2> ReadStsSigningCertificates(SecurityTokenServiceDescriptor stsDescriptor)
    {
        List <X509Certificate2> stsCertificates = new List <X509Certificate2>();

        if (stsDescriptor != null && stsDescriptor.Keys != null)
        {
            Collection <KeyDescriptor> keyDescriptors = (Collection <KeyDescriptor>)stsDescriptor.Keys;

            if (keyDescriptors != null && keyDescriptors.Count > 0)
            {
                foreach (KeyDescriptor keyDescriptor in keyDescriptors)
                {
                    if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                    {
                        SecurityKeyIdentifier          kid    = keyDescriptor.KeyInfo;
                        X509RawDataKeyIdentifierClause clause = null;

                        kid.TryFind <X509RawDataKeyIdentifierClause>(out clause);

                        if (clause != null)
                        {
                            X509Certificate2 certificate = new X509Certificate2(clause.GetX509RawData());
                            stsCertificates.Add(certificate);
                        }
                    }
                }
            }
        }

        return(stsCertificates);
    }
Exemple #2
0
 public static byte[] signingCertificate(string metadataURI)
 {
     if (metadataURI == null)
     {
         throw new ArgumentNullException(metadataURI);
     }
     using (XmlReader metadataReader = XmlReader.Create(metadataURI)) {
         MetadataSerializer serializer = new MetadataSerializer()
         {
             CertificateValidationMode = X509CertificateValidationMode.None
         };
         EntityDescriptor entityDescriptor = serializer.ReadMetadata(metadataReader) as EntityDescriptor;
         if (entityDescriptor != null)
         {
             SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
             if (stsd != null)
             {
                 X509RawDataKeyIdentifierClause clause = stsd.Keys.First().KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First();
                 if (clause != null)
                 {
                     return(clause.GetX509RawData());
                 }
                 throw new Exception("The SecurityTokenServiceDescriptor in the metadata does not contain a RawData signing certificate");
             }
             throw new Exception("The Federation Metadata document does not contain a SecurityTokenServiceDescriptor");
         }
         throw new Exception("Invalid Federation Metadata document");
     }
 }
Exemple #3
0
            public override void WriteKeyIdentifierClauseCore(XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause)
            {
                X509RawDataKeyIdentifierClause clause = keyIdentifierClause as X509RawDataKeyIdentifierClause;

                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, this.NamespaceUri);
                writer.WriteStartElement(XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Certificate, this.NamespaceUri);
                byte[] buffer = clause.GetX509RawData();
                writer.WriteBase64(buffer, 0, buffer.Length);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
Exemple #4
0
        static ClaimsPrincipal ValidateTokenWithX509SecurityToken(X509RawDataKeyIdentifierClause x509DataClause, string token)
        {
            var validatingCertificate = new X509Certificate2(x509DataClause.GetX509RawData());
            var tokenHandler          = new JwtSecurityTokenHandler();
            var x509SecurityToken     = new X509SecurityToken(validatingCertificate);
            var validationParameters  = new TokenValidationParameters()
            {
                AllowedAudience = "http://www.example.com",
                SigningToken    = x509SecurityToken,
                ValidIssuer     = "self",
            };

            ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(new JwtSecurityToken(token), validationParameters);

            return(claimsPrincipal);
        }
        /// <summary>
        /// Converts a SKI into one or more certificates for further processing.
        /// </summary>
        /// <param name="ski">SecurityKeyIdentifier to convert.</param>
        /// <returns>List of X509Certificate2 objects converted from the SKI.</returns>
        static List <X509Certificate2> GetCertificatesFromKeyInfo(SecurityKeyIdentifier ski)
        {
            List <X509Certificate2> certificates = new List <X509Certificate2>();

            foreach (SecurityKeyIdentifierClause keyClause in ski)
            {
                //
                // Only X509RawData clauses are supported. If any other clause is present, custom code
                // would be required to resolve the clause against some certificate store, such as the Windows
                // certificate store or a database. WIF exposes security token resolver classes which can
                // help with this resolution if needed.
                //
                X509RawDataKeyIdentifierClause x509KeyClause = keyClause as X509RawDataKeyIdentifierClause;
                if (x509KeyClause != null)
                {
                    byte[] certificateBytes = x509KeyClause.GetX509RawData();
                    certificates.Add(new X509Certificate2(certificateBytes));
                }
            }

            return(certificates);
        }
        /// <summary>
        /// Retrieves a populated <see cref="WsFederationConfiguration"/> given an address and an <see cref="IDocumentRetriever"/>.
        /// </summary>
        /// <param name="address">address of the metadata document.</param>
        /// <param name="retriever">the <see cref="IDocumentRetriever"/> to use to read the metadata document</param>
        /// <param name="cancel"><see cref="CancellationToken"/>.</param>
        /// <returns>A populated <see cref="WsFederationConfiguration"/> instance.</returns>
        public static async Task <WsFederationConfiguration> GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
        {
            if (string.IsNullOrWhiteSpace(address))
            {
                throw new ArgumentNullException("address");
            }

            if (retriever == null)
            {
                throw new ArgumentNullException("retriever");
            }

            WsFederationConfiguration configuration = new WsFederationConfiguration();

            string document = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);

            using (XmlReader metaDataReader = XmlReader.Create(new StringReader(document), SafeSettings))
            {
                var serializer = new MetadataSerializer {
                    CertificateValidationMode = X509CertificateValidationMode.None
                };

                MetadataBase metadataBase     = serializer.ReadMetadata(metaDataReader);
                var          entityDescriptor = (EntityDescriptor)metadataBase;

                if (!string.IsNullOrWhiteSpace(entityDescriptor.EntityId.Id))
                {
                    configuration.Issuer = entityDescriptor.EntityId.Id;
                }

                SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
                if (stsd != null)
                {
                    configuration.TokenEndpoint = stsd.PassiveRequestorEndpoints.First().Uri.AbsoluteUri;
                    foreach (KeyDescriptor keyDescriptor in stsd.Keys)
                    {
                        if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                        {
                            foreach (SecurityKeyIdentifierClause clause in keyDescriptor.KeyInfo)
                            {
                                X509RawDataKeyIdentifierClause x509Clause = clause as X509RawDataKeyIdentifierClause;
                                if (x509Clause != null)
                                {
                                    var key = new X509SecurityKey(new X509Certificate2(x509Clause.GetX509RawData()));
                                    configuration.SigningKeys.Add(key);
                                }
                            }
                        }
                    }
                }
            }

            return(configuration);
        }
        public static AuthMetadata GetWSFederationMetadata(string content)
        {
            AuthMetadata result;

            try
            {
                using (TextReader textReader = new StringReader(content))
                {
                    using (XmlReader xmlReader = XmlReader.Create(textReader))
                    {
                        MetadataSerializer metadataSerializer = new MetadataSerializer
                        {
                            CertificateValidationMode = X509CertificateValidationMode.None
                        };
                        EntityDescriptor entityDescriptor = metadataSerializer.ReadMetadata(xmlReader) as EntityDescriptor;
                        SecurityTokenServiceDescriptor securityTokenServiceDescriptor = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First <SecurityTokenServiceDescriptor>();
                        List <string> list = new List <string>();
                        foreach (KeyDescriptor keyDescriptor in from k in securityTokenServiceDescriptor.Keys
                                 where k.Use == KeyType.Signing
                                 select k)
                        {
                            foreach (SecurityKeyIdentifierClause securityKeyIdentifierClause in keyDescriptor.KeyInfo)
                            {
                                X509RawDataKeyIdentifierClause x509RawDataKeyIdentifierClause = securityKeyIdentifierClause as X509RawDataKeyIdentifierClause;
                                if (x509RawDataKeyIdentifierClause != null)
                                {
                                    list.Add(Convert.ToBase64String(x509RawDataKeyIdentifierClause.GetX509RawData()));
                                }
                            }
                        }
                        AuthMetadata authMetadata = new AuthMetadata();
                        authMetadata.CertificateStrings = list.ToArray();
                        string serviceName;
                        string realm;
                        if (AuthMetadataParser.TryExtractUrlFormatServiceNameAndRealm(entityDescriptor.EntityId.Id, out serviceName, out realm))
                        {
                            authMetadata.ServiceName = serviceName;
                            authMetadata.Realm       = realm;
                        }
                        else
                        {
                            authMetadata.ServiceName = entityDescriptor.EntityId.Id;
                            authMetadata.Realm       = null;
                        }
                        if (string.IsNullOrEmpty(authMetadata.ServiceName))
                        {
                            throw new AuthMetadataParserException(DirectoryStrings.ErrorAuthMetadataCannotResolveServiceName);
                        }
                        result = authMetadata;
                    }
                }
            }
            catch (XmlException innerException)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException);
            }
            catch (IOException innerException2)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException2);
            }
            catch (SecurityException innerException3)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException3);
            }
            catch (SystemException innerException4)
            {
                throw new AuthMetadataParserException(DirectoryStrings.ErrorCannotParseAuthMetadata, innerException4);
            }
            return(result);
        }