private static SecurityTokenServiceDescriptor CreateSecurityTokenServiceDescriptor(X509SigningCredentials credentials,
                                                                                           EndpointReference passiveEndpoint)
        {
            var sts = new SecurityTokenServiceDescriptor();

            // Add STS's signing key
            var signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);
            return(sts);
        }
    /// <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);
    }
    //
    // Private constructor for Singleton.
    //
    private LiveStsFederationMetadata()
    {
        MetadataBase metadataBase = LoadMetadata();
        SecurityTokenServiceDescriptor stsDescriptor = ReadStsDescriptor(metadataBase);

        _signingCertificates = ReadStsSigningCertificates(stsDescriptor);
    }
Пример #4
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");
     }
 }
Пример #5
0
        static void CreatePassiveStsMetadata(StsData data, string fileName, Encoding encoding)
        {
            MetadataSerializer             serializer = new MetadataSerializer();
            SecurityTokenServiceDescriptor item       = new SecurityTokenServiceDescriptor();
            EntityDescriptor metadata = new EntityDescriptor();

            metadata.EntityId = new EntityId(data.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(data.SigninCertificateCn);

            metadata.SigningCredentials = new X509SigningCredentials(certificate);
            KeyDescriptor descriptor3 = new KeyDescriptor(new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { new X509SecurityToken(certificate).CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>() }));

            descriptor3.Use = KeyType.Signing;
            item.Keys.Add(descriptor3);

            if (data.Claims != null)
            {
                foreach (var claim in data.Claims)
                {
                    DisplayClaim dc = new DisplayClaim(claim.ClaimType, claim.DisplayTag, claim.Description)
                    {
                        Optional = claim.Optional
                    };

                    item.ClaimTypesOffered.Add(dc);
                }
            }

            item.PassiveRequestorEndpoints.Add(new EndpointAddress(new Uri(data.PassiveRequestorEndpoint).AbsoluteUri));

            if (data.Protocols != null)
            {
                foreach (Protocol protocol in data.Protocols)
                {
                    item.ProtocolsSupported.Add(new Uri(protocol.ProtocolNamespace));
                }
            }


            item.SecurityTokenServiceEndpoints.Add(new EndpointAddress(new Uri(data.ActiveStsEndpoint).AbsoluteUri));
            item.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company          = data.MainContact.Company,
                GivenName        = data.MainContact.GivenName,
                Surname          = data.MainContact.SurName,
                EmailAddresses   = { data.MainContact.Email },
                TelephoneNumbers = { data.MainContact.Phone }
            });

            metadata.RoleDescriptors.Add(item);



            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);

            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
        private void FillSigningKey(SecurityTokenServiceDescriptor sts)
        {
            KeyDescriptor signingKey = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            sts.Keys.Add(signingKey);
        }
Пример #7
0
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor()
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.JsonWebToken));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));
            tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(OAuthTokenEndpoint));

            return(tokenService);
        }
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string passiveRequestorEndpoint)
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.ServiceDescription = ConfigurationRepository.Global.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(passiveRequestorEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml2TokenProfile11));

            ClaimsRepository.GetSupportedClaimTypes()
            .ToList()
            .ForEach(claimType => tokenService.ClaimTypesOffered.Add(new DisplayClaim(claimType)));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMessageSecurity)
            {
                var addressMessageUserName = new EndpointAddress(_endpoints.WSTrustMessageUserName, null, null,
                                                                 CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(
                    new EndpointReference(addressMessageUserName.Uri.AbsoluteUri));

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var addressMessageCertificate = new EndpointAddress(_endpoints.WSTrustMessageCertificate, null, null,
                                                                        CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(
                        new EndpointReference(addressMessageCertificate.Uri.AbsoluteUri));
                }
            }
            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMixedModeSecurity)
            {
                var addressMixedUserName = new EndpointAddress(_endpoints.WSTrustMixedUserName, null, null,
                                                               CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(
                    new EndpointReference(addressMixedUserName.Uri.AbsoluteUri));

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var addressMixedCertificate = new EndpointAddress(_endpoints.WSTrustMixedCertificate, null, null,
                                                                      CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(
                        new EndpointReference(addressMixedCertificate.Uri.AbsoluteUri));
                }
            }

            if (tokenService.SecurityTokenServiceEndpoints.Count == 0)
            {
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(_endpoints.WSFederation.AbsoluteUri));
            }

            return(tokenService);
        }
Пример #9
0
        /// <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))
            {
                LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": address"), typeof(ArgumentNullException), EventLevel.Verbose);
            }

            if (retriever == null)
            {
                LogHelper.Throw(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, GetType() + ": retriever"), typeof(ArgumentNullException), EventLevel.Verbose);
            }

            WsFederationConfiguration configuration = new WsFederationConfiguration();

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

            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))
                        {
                            IdentityModelEventSource.Logger.WriteVerbose(LogMessages.IDX10807);
                            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);
        }
Пример #10
0
    /// <summary>
    /// Generate a sample MetadataBase.
    /// </summary>
    /// <remarks>
    /// In a production system this would be generated from the STS configuration.
    /// </remarks>
    public static MetadataBase GetFederationMetadata()
    {
        string           endpointId = "http://localhost/stsservice/service.svc";
        EntityDescriptor metadata   = new EntityDescriptor();

        metadata.EntityId = new EntityId(endpointId);

        // Define the signing key
        string           signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
        X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);

        metadata.SigningCredentials = new X509SigningCredentials(cert);

        // Create role descriptor for security token service
        SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();

        stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
        metadata.RoleDescriptors.Add(stsRole);

        // Add a contact name
        ContactPerson person = new ContactPerson(ContactType.Administrative);

        person.GivenName = "contactName";
        stsRole.Contacts.Add(person);

        // Include key identifier for signing key in metadata
        SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
        SecurityKeyIdentifier       ski    = new SecurityKeyIdentifier(clause);
        KeyDescriptor signingKey           = new KeyDescriptor(ski);

        signingKey.Use = KeyType.Signing;
        stsRole.Keys.Add(signingKey);

        // Add endpoints
        string          activeSTSUrl    = "https://localhost/stsservice/service.svc";
        EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                              null,
                                                              null, GetMetadataReader(activeSTSUrl), null);

        stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

        // Add a collection of offered claims
        // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
        //       In a production system, there would be some common data store that both use
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
        // Add a special claim for the QuoteService
        stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

        return(metadata);
    }
        public string GetFederationMetadata(Uri endpoint)
        {
            // hostname
            var passiveEndpoint = new EndpointReference(endpoint.AbsoluteUri);
            var activeEndpoint  = new EndpointReference(endpoint.AbsoluteUri);

            // metadata document
            var entity = new EntityDescriptor(new EntityId(TwitterClaims.IssuerName));
            var sts    = new SecurityTokenServiceDescriptor();

            entity.RoleDescriptors.Add(sts);

            // signing key
            var signingKey = new KeyDescriptor(SigningCredentials.SigningKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            sts.Keys.Add(signingKey);

            // claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "User name"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.NameIdentifier, "Name Identifier", "User name identifier"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterToken, "Token", "Service token"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterTokenSecret, "Token Secret", "Service token secret"));

            // passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // supported protocols

            //Inaccessable due to protection level
            //sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));
            sts.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            // add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(activeEndpoint);

            // metadata signing
            entity.SigningCredentials = SigningCredentials;

            // serialize
            var serializer = new MetadataSerializer();

            using (var memoryStream = new MemoryStream())
            {
                serializer.WriteMetadata(memoryStream, entity);
                return(Encoding.UTF8.GetString(memoryStream.ToArray()));
            }
        }
 private EntityDescriptor GenerateEntities()
 {
     var sts = new SecurityTokenServiceDescriptor();
     FillOfferedClaimTypes(sts.ClaimTypesOffered);
     FillEndpoints(sts);
     FillSupportedProtocols(sts);
     FillSigningKey(sts);
     var entity = new EntityDescriptor(new EntityId(string.Format("https://{0}", Request.Url.GetLeftPart(UriPartial.Authority))))
     {
         SigningCredentials = this.SigningCredentials
     };
     entity.RoleDescriptors.Add(sts);
     return entity;
 }
        public void Metadata()
        {
            var config = new SimpleSecurityTokenServiceConfiguration();   

            // Entity
            var ent = new EntityDescriptor();
            ent.Contacts.Add(new ContactPerson(ContactType.Technical) { GivenName = "Sandra", Surname = "Fernandes" });
            ent.EntityId = new EntityId(config.TokenIssuerName);
            ent.SigningCredentials = config.SigningCredentials;

            // Role: Security Token Service
            var role = new SecurityTokenServiceDescriptor();
            var endpoints = new EndpointAddress[] {
                new EndpointAddress("https://idp.prompt11.local:10443/Federation/Issue"),                
            };
            foreach (var ep in endpoints)
            {
                role.SecurityTokenServiceEndpoints.Add(ep);
                role.PassiveRequestorEndpoints.Add(ep);
            }

            role.ServiceDescription = "My Service";
            role.ServiceDisplayName = "My Service Description";
            role.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));
            role.ValidUntil = DateTime.Now.AddDays(1);
            role.ClaimTypesOffered.Add(new DisplayClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Role));
            role.ClaimTypesOffered.Add(new DisplayClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Name));

            role.Keys.Add(
                new KeyDescriptor()
                {
                    KeyInfo =
                        new SecurityKeyIdentifier(
                            new X509RawDataKeyIdentifierClause((config.SigningCredentials as X509SigningCredentials).Certificate)
                        ),
                    Use = KeyType.Signing
                }
            );

            ent.RoleDescriptors.Add(role);

            // Serialize
            var serializer = new MetadataSerializer();
            var xe = new XDocument();
            var writer = xe.CreateWriter();
            serializer.WriteMetadata(writer, ent);
            writer.Close();
            Response.ContentType = "text/xml";
            Response.Write(xe.ToString(SaveOptions.DisableFormatting));     
        }
        //[Authorize]
        public ActionResult FederationMetadata()
        {
            var endpoint         = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port;
            var entityDescriptor = new EntityDescriptor(
                new EntityId(ConfigurationManager.AppSettings["stsName"]))
            {
                SigningCredentials = CertificateFactory.GetSigningCredentials()
            };

            var roleDescriptor = new SecurityTokenServiceDescriptor();

            roleDescriptor.Contacts.Add(new ContactPerson(ContactType.Administrative));

            var clause = new X509RawDataKeyIdentifierClause(CertificateFactory.GetCertificate());
            var securityKeyIdentifier = new SecurityKeyIdentifier(clause);
            var signingKey            = new KeyDescriptor(securityKeyIdentifier)
            {
                Use = KeyType.Signing
            };

            roleDescriptor.Keys.Add(signingKey);

            var endpointAddress =
                new System.IdentityModel.Protocols.WSTrust.EndpointReference(endpoint + "/Security/Authorize");

            roleDescriptor.PassiveRequestorEndpoints.Add(endpointAddress);
            roleDescriptor.SecurityTokenServiceEndpoints.Add(endpointAddress);

            roleDescriptor.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            entityDescriptor.RoleDescriptors.Add(roleDescriptor);

            var serializer = new MetadataSerializer();
            var settings   = new XmlWriterSettings {
                Encoding = Encoding.UTF8
            };

            var memoryStream = new MemoryStream();
            var writer       = XmlWriter.Create(memoryStream, settings);

            serializer.WriteMetadata(writer, entityDescriptor);
            writer.Flush();

            var content = Content(Encoding.UTF8.GetString(memoryStream.GetBuffer()), "text/xml");

            writer.Dispose();

            return(content);
        }
    private SecurityTokenServiceDescriptor ReadStsDescriptor(MetadataBase metadataBase)
    {
        EntitiesDescriptor entities = metadataBase as EntitiesDescriptor;

        if (entities != null)
        {
            foreach (EntityDescriptor en in entities.ChildEntities)
            {
                foreach (RoleDescriptor role in en.RoleDescriptors)
                {
                    SecurityTokenServiceDescriptor stsDescriptor = role as SecurityTokenServiceDescriptor;
                    if (stsDescriptor != null)
                    {
                        //
                        // If there are multiple STS descriptors, the first one listed will be used.
                        // This mirrors the behavior of the Federation Utility tool that creates automatic trust
                        // using the STS Federation metadata. This is provided for illustrative purposes only.
                        // In a production system, you may choose to trust one or more STS descriptors that are
                        // published in the STS Federation metadata.
                        //
                        return(stsDescriptor);
                    }
                }
            }
        }

        EntityDescriptor entity = metadataBase as EntityDescriptor;

        if (entity != null)
        {
            foreach (RoleDescriptor role in entity.RoleDescriptors)
            {
                SecurityTokenServiceDescriptor stsDescriptor = role as SecurityTokenServiceDescriptor;
                if (stsDescriptor != null)
                {
                    //
                    // If there are multiple STS descriptors, the first one listed will be used.
                    // This mirrors the behavior of the Federation Utility tool that creates automatic trust
                    // using the STS Federation metadata. This is provided for illustrative purposes only.
                    // In a production system, you may choose to trust one or more STS descriptors that are
                    // published in the STS Federation metadata.
                    //
                    return(stsDescriptor);
                }
            }
        }

        throw new InvalidOperationException("The metadata does not contain a valid SecurityTokenServiceDescriptor.");
    }
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string wsfedEndpoint, X509Certificate2 cert)
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.ServiceDescription = "IdentityServer4 WS-Federation Endpoint";
            tokenService.Keys.Add(GetSigningKeyDescriptor(cert));

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(wsfedEndpoint));
            tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(wsfedEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"));
            tokenService.TokenTypesOffered.Add(new Uri("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            return(tokenService);
        }
Пример #17
0
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor()
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.ServiceDescription = ConfigurationRepository.Configuration.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointAddress(_endpoints.WSFederation));

            tokenService.TokenTypesOffered.Add(new Uri(Microsoft.IdentityModel.Tokens.SecurityTokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(Microsoft.IdentityModel.Tokens.SecurityTokenTypes.OasisWssSaml2TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(SimpleWebToken.OasisTokenProfile));

            ClaimsRepository.GetSupportedClaimTypes().ToList().ForEach(claimType => tokenService.ClaimTypesOffered.Add(new DisplayClaim(claimType)));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            if (ConfigurationRepository.Endpoints.WSTrustMessage)
            {
                var addressMessageUserName = new EndpointAddress(_endpoints.WSTrustMessageUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(addressMessageUserName);

                if (ConfigurationRepository.Configuration.EnableClientCertificates)
                {
                    var addressMessageCertificate = new EndpointAddress(_endpoints.WSTrustMessageCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(addressMessageCertificate);
                }
            }
            if (ConfigurationRepository.Endpoints.WSTrustMixed)
            {
                var addressMixedUserName = new EndpointAddress(_endpoints.WSTrustMixedUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(addressMixedUserName);

                if (ConfigurationRepository.Configuration.EnableClientCertificates)
                {
                    var addressMixedCertificate = new EndpointAddress(_endpoints.WSTrustMixedCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(addressMixedCertificate);
                }
            }

            if (tokenService.SecurityTokenServiceEndpoints.Count == 0)
            {
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointAddress(_endpoints.WSFederation));
            }

            return(tokenService);
        }
Пример #18
0
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string wsfedEndpoint)
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.ServiceDescription = _options.IssuerName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(wsfedEndpoint));
            tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(wsfedEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"));
            tokenService.TokenTypesOffered.Add(new Uri("urn:ietf:params:oauth:token-type:jwt"));

            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            return(tokenService);
        }
Пример #19
0
        internal static IssuerSigningKeys GetSigningKeys(string AzureFedUrl)
        {
            string issuer = "";
            List <X509SecurityToken> tokens = new List <X509SecurityToken>();

            var responseStatus = AzureFedUrl.GetResponseStatus();

            if (responseStatus.HasValue && responseStatus.Value == System.Net.HttpStatusCode.OK)
            {
                using (XmlReader xmlReader = XmlReader.Create(AzureFedUrl))
                {
                    var mdSerializer = new MetadataSerializer {
                        CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None
                    };
                    MetadataBase metadata      = mdSerializer.ReadMetadata(xmlReader);
                    var          entDescriptor = (EntityDescriptor)metadata;

                    //get the issues
                    if (!string.IsNullOrWhiteSpace(entDescriptor.EntityId.Id))
                    {
                        issuer = entDescriptor.EntityId.Id;
                    }

                    //get security token info
                    SecurityTokenServiceDescriptor stsd = entDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
                    if (stsd == null)
                    {
                        throw new InvalidOperationException("No SecurityTokenServiceType descriptor in metadata.");
                    }

                    IEnumerable <X509RawDataKeyIdentifierClause> x509DataClauses =
                        stsd.Keys.Where(key => key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified))
                        .Select(key => key.KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First());

                    tokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new X509Certificate2(token.GetX509RawData()))));
                }
            }
            else
            {
                throw new InvalidOperationException("Unable to connect to federated trust url.");
            }
            return(new IssuerSigningKeys()
            {
                Issuer = issuer, Tokens = tokens
            });
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            EndpointAddress realm           = new EndpointAddress(identifier);
            EndpointAddress passiveEndpoint = new EndpointAddress(passiveSignInUrl);

            // Create metadata document for relying party
            EntityDescriptor entity            = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();

            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);

            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream       stream     = new MemoryStream();

            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return(stream.ToArray());
        }
        public static IssuerFederationData GetFederationMetataData(string metadataEndpoint, HttpClient metadataRequest)
        {
            string issuer = string.Empty;
            string passiveTokenEndpoint            = string.Empty;
            List <X509SecurityToken> signingTokens = new List <X509SecurityToken>();

            // TODO: Any way to make this async?
            using (HttpResponseMessage metadataResponse = metadataRequest.GetAsync(metadataEndpoint).Result)
            {
                metadataResponse.EnsureSuccessStatusCode();
                Stream metadataStream = metadataResponse.Content.ReadAsStreamAsync().Result;
                using (XmlReader metaDataReader = XmlReader.Create(metadataStream, SafeSettings))
                {
                    var serializer = new MetadataSerializer {
                        CertificateValidationMode = X509CertificateValidationMode.None
                    };

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

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

                    SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
                    if (stsd == null)
                    {
                        throw new InvalidOperationException(Resources.Exception_MissingDescriptor);
                    }

                    passiveTokenEndpoint = stsd.PassiveRequestorEndpoints.First().Uri.AbsoluteUri;

                    IEnumerable <X509RawDataKeyIdentifierClause> x509DataClauses =
                        stsd.Keys.Where(key => key.KeyInfo != null &&
                                        (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified))
                        .Select(key => key.KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First());

                    signingTokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new X509Certificate2(token.GetX509RawData()))));
                }
            }

            return(new IssuerFederationData {
                IssuerSigningTokens = signingTokens, PassiveTokenEndpoint = passiveTokenEndpoint, TokenIssuerName = issuer
            });
        }
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string wsfedEndpoint)
        {
            var tokenService = new SecurityTokenServiceDescriptor();
            tokenService.ServiceDescription = _options.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(wsfedEndpoint));
            tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(wsfedEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml2TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.JsonWebToken));

            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            return tokenService;
        }
Пример #23
0
        public static IssuerSigningKeys GetSigningKeys(string metadataEndpoint, TimeSpan backchannelTimeout, HttpMessageHandler backchannelHttpHandler)
        {
            string issuer = string.Empty;
            var    tokens = new List <X509SecurityToken>();

            using (var metadataRequest = new HttpClient(backchannelHttpHandler, false))
            {
                metadataRequest.Timeout = backchannelTimeout;
                using (HttpResponseMessage metadataResponse = metadataRequest.GetAsync(metadataEndpoint).Result)
                {
                    metadataResponse.EnsureSuccessStatusCode();
                    Stream metadataStream = metadataResponse.Content.ReadAsStreamAsync().Result;
                    using (XmlReader metaDataReader = XmlReader.Create(metadataStream, SafeSettings))
                    {
                        var serializer = new MetadataSerializer {
                            CertificateValidationMode = X509CertificateValidationMode.None
                        };

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

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

                        SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();
                        if (stsd == null)
                        {
                            throw new InvalidOperationException(Properties.Resources.Exception_MissingDescriptor);
                        }

                        IEnumerable <X509RawDataKeyIdentifierClause> x509DataClauses =
                            stsd.Keys.Where(key => key.KeyInfo != null &&
                                            (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified))
                            .Select(key => key.KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First());
                        tokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new X509Certificate2(token.GetX509RawData()))));
                    }
                }
            }

            return(new IssuerSigningKeys {
                Issuer = issuer, Tokens = tokens
            });
        }
Пример #24
0
        /// <summary>
        /// Generate a sample MetadataBase.
        /// </summary>
        /// <remarks>
        /// In a production system this would be generated from the STS configuration.
        /// </remarks>
        public static MetadataBase GetFederationMetadata()
        {
            string endpointId = "http://localhost:61754/";
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(endpointId);

            // Define the signing key
            string signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);
            metadata.SigningCredentials = new X509SigningCredentials(cert);

            // Create role descriptor for security token service
            SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
            stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
            metadata.RoleDescriptors.Add(stsRole);

            // Add a contact name
            ContactPerson person = new ContactPerson(ContactType.Administrative);
            person.GivenName = "contactName";
            stsRole.Contacts.Add(person);

            // Include key identifier for signing key in metadata
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
            SecurityKeyIdentifier ski = new SecurityKeyIdentifier(clause);
            KeyDescriptor signingKey = new KeyDescriptor(ski);
            signingKey.Use = KeyType.Signing;
            stsRole.Keys.Add(signingKey);

            // Add endpoints
            string activeSTSUrl = "http://localhost:61754/";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                                   null,
                                                                   null, GetMetadataReader(activeSTSUrl), null);
            stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

            // Add a collection of offered claims
            // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
            //       In a production system, there would be some common data store that both use
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
            // Add a special claim for the QuoteService
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

            return metadata;
        }
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string wsfedEndpoint)
        {
            var tokenService = new SecurityTokenServiceDescriptor();

            tokenService.ServiceDescription = _settings.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(wsfedEndpoint));
            tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(wsfedEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml2TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.JsonWebToken));

            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            return(tokenService);
        }
        public void ShouldRoundTripSecurityTokenService()
        {
            var descriptor = new SecurityTokenServiceDescriptor();
            var securityTokenServiceEndpoint = new EndpointReferenceCollection();

            securityTokenServiceEndpoint.Add(new EndpointReference {
                Address = new Uri("https://notused")
            });
            descriptor.SecurityTokenServiceEndpoint.Add(securityTokenServiceEndpoint);
            descriptor.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            var xml = _serializer.WriteRoleDescriptor(descriptor);

            var deserialized = _serializer.ReadRoleDescriptor(xml);

            Assert.IsType <SecurityTokenServiceDescriptor>(deserialized);
            AssertEqual(descriptor, deserialized);
        }
        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor()
        {
            var tokenService = new SecurityTokenServiceDescriptor();
            tokenService.ServiceDescription = ConfigurationRepository.Configuration.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointAddress(_endpoints.WSFederation));

            tokenService.TokenTypesOffered.Add(new Uri(Microsoft.IdentityModel.Tokens.SecurityTokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(Microsoft.IdentityModel.Tokens.SecurityTokenTypes.OasisWssSaml2TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(SimpleWebToken.OasisTokenProfile));

            UserRepository.GetSupportedClaimTypes().ToList().ForEach(claimType => tokenService.ClaimTypesOffered.Add(new DisplayClaim(claimType)));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            if (ConfigurationRepository.Endpoints.WSTrustMessage)
            {
                var addressMessageUserName = new EndpointAddress(_endpoints.WSTrustMessageUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(addressMessageUserName);

                if (ConfigurationRepository.Configuration.EnableClientCertificates)
                {
                    var addressMessageCertificate = new EndpointAddress(_endpoints.WSTrustMessageCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(addressMessageCertificate);
                }
            }
            if (ConfigurationRepository.Endpoints.WSTrustMixed)
            {
                var addressMixedUserName = new EndpointAddress(_endpoints.WSTrustMixedUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(addressMixedUserName);

                if (ConfigurationRepository.Configuration.EnableClientCertificates)
                {
                    var addressMixedCertificate = new EndpointAddress(_endpoints.WSTrustMixedCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(addressMixedCertificate);
                }
            }

            if (tokenService.SecurityTokenServiceEndpoints.Count == 0)
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointAddress(_endpoints.WSFederation));

            return tokenService;
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            EndpointAddress realm = new EndpointAddress(identifier);
            EndpointAddress passiveEndpoint = new EndpointAddress(passiveSignInUrl);

            // Create metadata document for relying party
            EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);
            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream stream = new MemoryStream();
            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return stream.ToArray();
        }
Пример #29
0
        /// <summary>
        ///  Returns a list of certificates from the specified metadata document.
        /// </summary>
        /// <param name="metadataAddress"></param>
        /// <returns></returns>

        private static List <X509SecurityToken> GetSigningCertificates(string metadataAddress)
        {
            List <X509SecurityToken> tokens = new List <X509SecurityToken>();

            if (metadataAddress == null)
            {
                throw new ArgumentNullException(metadataAddress);
            }

            using (XmlReader metadataReader = XmlReader.Create(metadataAddress))
            {
                MetadataSerializer serializer = new MetadataSerializer()
                {
                    // Do not disable for production code
                    CertificateValidationMode = X509CertificateValidationMode.None
                };

                EntityDescriptor metadata = serializer.ReadMetadata(metadataReader) as EntityDescriptor;

                if (metadata != null)
                {
                    SecurityTokenServiceDescriptor stsd = metadata.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();

                    if (stsd != null)
                    {
                        IEnumerable <X509RawDataKeyIdentifierClause> x509DataClauses = stsd.Keys.Where(key => key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified)).
                                                                                       Select(key => key.KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First());

                        tokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new X509Certificate2(token.GetX509RawData()))));
                    }
                    else
                    {
                        throw new InvalidOperationException("There is no RoleDescriptor of type SecurityTokenServiceType in the metadata");
                    }
                }
                else
                {
                    throw new Exception("Invalid Federation Metadata document");
                }
            }
            return(tokens);
        }
        static List <X509SecurityToken> ReadSigningCertsFromMetadata(EntityDescriptor entityDescriptor)
        {
            List <X509SecurityToken> stsSigningTokens = new List <X509SecurityToken>();

            SecurityTokenServiceDescriptor stsd = entityDescriptor.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().First();

            if (stsd != null)
            {
                IEnumerable <X509RawDataKeyIdentifierClause> x509DataClauses = stsd.Keys.Where(key => key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified)).
                                                                               Select(key => key.KeyInfo.OfType <X509RawDataKeyIdentifierClause>().First());

                stsSigningTokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new X509Certificate2(token.GetX509RawData()))));
            }
            else
            {
                throw new InvalidOperationException("There is no RoleDescriptor of type SecurityTokenServiceType in the metadata");
            }

            return(stsSigningTokens);
        }
        public XElement GetFederationMetadata(string endPoint, IList <string> claims)
        {
            System.ServiceModel.EndpointAddress item = new System.ServiceModel.EndpointAddress(endPoint + "/_sts/");
            EntityDescriptor entityDescriptor        = new EntityDescriptor(new EntityId(this.TokenIssuerName));
            SecurityTokenServiceDescriptor securityTokenServiceDescriptor = new SecurityTokenServiceDescriptor();

            entityDescriptor.RoleDescriptors.Add(securityTokenServiceDescriptor);
            KeyDescriptor keyDescriptor = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier);

            keyDescriptor.Use = KeyType.Signing;
            securityTokenServiceDescriptor.Keys.Add(keyDescriptor);
            for (int i = 0; i < claims.Count; i++)
            {
                securityTokenServiceDescriptor.ClaimTypesOffered.Add(new DisplayClaim(claims[i], claims[i], string.Empty));
            }

            var endPointReference = new EndpointReference(item.Uri.ToString());

            securityTokenServiceDescriptor.PassiveRequestorEndpoints.Add(endPointReference);
            securityTokenServiceDescriptor.ProtocolsSupported.Add(new System.Uri("http://docs.oasis-open.org/wsfed/federation/200706"));
            securityTokenServiceDescriptor.SecurityTokenServiceEndpoints.Add(endPointReference);
            entityDescriptor.SigningCredentials = base.SigningCredentials;
            MetadataSerializer metadataSerializer = new MetadataSerializer();
            XElement           result             = null;

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                metadataSerializer.WriteMetadata(memoryStream, entityDescriptor);
                memoryStream.Flush();
                memoryStream.Seek(0L, System.IO.SeekOrigin.Begin);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments   = true;
                settings.IgnoreWhitespace = true;
                XmlReader reader = XmlReader.Create(memoryStream);
                result = XElement.Load(reader);
            }


            return(result);
        }
 private void FillSupportedProtocols(SecurityTokenServiceDescriptor sts)
 {
     sts.ProtocolsSupported.Add(new System.Uri(WSFederationConstants.Namespace));
 }
 private void FillEndpoints(SecurityTokenServiceDescriptor sts)
 {
     var endpoint = new EndpointAddress(string.Format("http://{0}", Request.Url.GetLeftPart(UriPartial.Authority)));
     sts.SecurityTokenServiceEndpoints.Add(endpoint);
     sts.PassiveRequestorEndpoints.Add(endpoint);
 }
Пример #34
0
        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);
        }
        static void CreatePassiveStsMetadata(StsData data, string fileName, Encoding encoding)
        {
            MetadataSerializer serializer = new MetadataSerializer();
            SecurityTokenServiceDescriptor item = new SecurityTokenServiceDescriptor();
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(data.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(data.SigninCertificateCn);

            metadata.SigningCredentials = new X509SigningCredentials(certificate);
            KeyDescriptor descriptor3 = new KeyDescriptor(new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() }));
            descriptor3.Use = KeyType.Signing;
            item.Keys.Add(descriptor3);

            if (data.Claims != null)
            {
                foreach (var claim in data.Claims)
                {
                    DisplayClaim dc = new DisplayClaim(claim.ClaimType, claim.DisplayTag, claim.Description)
                    {
                        Optional = claim.Optional
                    };

                    item.ClaimTypesOffered.Add(dc);
                }
            }

            item.PassiveRequestorEndpoints.Add(new EndpointAddress( new Uri(data.PassiveRequestorEndpoint).AbsoluteUri));

            if (data.Protocols != null)
            {
                foreach (Protocol protocol in data.Protocols)
                {
                    item.ProtocolsSupported.Add(new Uri(protocol.ProtocolNamespace));
                }
            }

            item.SecurityTokenServiceEndpoints.Add(new EndpointAddress( new Uri(data.ActiveStsEndpoint).AbsoluteUri));
            item.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = data.MainContact.Company,
                GivenName = data.MainContact.GivenName,
                Surname = data.MainContact.SurName,
                EmailAddresses = { data.MainContact.Email },
                TelephoneNumbers = { data.MainContact.Phone }
            });

            metadata.RoleDescriptors.Add(item);

            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
Пример #36
0
        public XElement GetFederationMetadata()
        {
            // hostname
            EndpointReference passiveEndpoint = new EndpointReference(Constants.HttpLocalhost + Constants.Port + Constants.WSFedStsIssue);
            EndpointReference activeEndpoint  = new EndpointReference(Constants.HttpLocalhost + Constants.Port + Constants.WSTrustSTS);

            // metadata document
            EntityDescriptor entity            = new EntityDescriptor(new EntityId(Constants.IssuerName));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();

            entity.RoleDescriptors.Add(sts);

            // signing key
            KeyDescriptor signingKey = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier);

            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Email, "Email Address", "User email address"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Surname, "Surname", "User last name"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "User name"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "Roles user are in"));
            sts.ClaimTypesOffered.Add(new DisplayClaim("http://schemas.xmlsoap.org/claims/Group", "Group", "Groups users are in"));

            // passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // supported protocols

            //Inaccessable due to protection level
            //sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));
            sts.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            // add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(activeEndpoint);

            // metadata signing
            entity.SigningCredentials = this.SigningCredentials;

            // serialize
            var      serializer         = new MetadataSerializer();
            XElement federationMetadata = null;

            using (var stream = new MemoryStream())
            {
                serializer.WriteMetadata(stream, entity);
                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                XmlReaderSettings readerSettings = new XmlReaderSettings
                {
                    DtdProcessing = DtdProcessing.Prohibit, // prohibit DTD processing
                    XmlResolver   = null,                   // disallow opening any external resources
                    // no need to do anything to limit the size of the input, given the input is crafted internally and it is of small size
                };

                XmlReader xmlReader = XmlTextReader.Create(stream, readerSettings);
                federationMetadata = XElement.Load(xmlReader);
            }

            return(federationMetadata);
        }
Пример #37
0
        /// <summary>
        ///     Configure ACS endpoint address in Web.config.
        /// </summary>
        public static void Intialize()
        {
            // Compute federation metadata address based on web config's
            // <system.identityModel.services>\<federationConfiguration>\<wsFederation issuer=""> attribute value
            var    settings     = DependencyResolver.Current.GetService <IPortalFrontendSettings>();
            string acsNamespace = settings.AcsNamespace;

            // Setup correct issuer name
            // Compute federation metadata address based on web config's
            // <system.identityModel.services>\<federationConfiguration>\<wsFederation issuer=""> attribute value
            string stsMetadataAddress = string.Format(WsFederationMetadata, acsNamespace);

            // Update the web config with latest local STS federation meta data each
            // time when instance of the application is created
            try
            {
                using (XmlReader metadataReader = XmlReader.Create(stsMetadataAddress))
                {
                    // Creates the xml reader pointing to the updated web.config contents
                    // Don't validate the cert signing the federation metadata
                    var serializer = new MetadataSerializer
                    {
                        CertificateValidationMode = X509CertificateValidationMode.None,
                    };

                    var metadata = (EntityDescriptor)serializer.ReadMetadata(metadataReader);

                    // Select security token descriptors
                    SecurityTokenServiceDescriptor descriptor = metadata.RoleDescriptors.OfType <SecurityTokenServiceDescriptor>().FirstOrDefault();
                    if (descriptor != null)
                    {
                        var issuerNameRegistry = new ConfigurationBasedIssuerNameRegistry();

                        // Try to find and add certificates for trusted issuers
                        foreach (KeyDescriptor keyDescriptor in descriptor.Keys)
                        {
                            if (keyDescriptor.KeyInfo != null && (keyDescriptor.Use == KeyType.Signing || keyDescriptor.Use == KeyType.Unspecified))
                            {
                                SecurityKeyIdentifier          keyInfo = keyDescriptor.KeyInfo;
                                X509RawDataKeyIdentifierClause clause;
                                keyInfo.TryFind(out clause);

                                if (clause != null)
                                {
                                    var x509Certificate2 = new X509Certificate2(clause.GetX509RawData());
                                    if (x509Certificate2.Thumbprint != null)
                                    {
                                        issuerNameRegistry.AddTrustedIssuer(x509Certificate2.Thumbprint, x509Certificate2.SubjectName.Name);
                                    }
                                }
                            }
                        }

                        // Set retrieved issuers
                        FederatedAuthentication.FederationConfiguration.IdentityConfiguration.IssuerNameRegistry = issuerNameRegistry;
                    }
                    metadataReader.Dispose();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Error occured when update web config with latest local STS federation meta data. {0}", e);
                return;
            }

            // Add audience URIs
            string portalUri = settings.PortalUri;

            // Front-end
            var uriBuilder = new UriBuilder(portalUri);

            FederatedAuthentication.FederationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(uriBuilder.Uri);

            // Extension
            uriBuilder.Path = "/extension/login";
            FederatedAuthentication.FederationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(uriBuilder.Uri);

            // Update WS-Federation configuration
            FederatedAuthentication.WSFederationAuthenticationModule.Issuer = string.Format(WsFederationIssuer, acsNamespace);
            FederatedAuthentication.WSFederationAuthenticationModule.Realm  = portalUri;
        }