/// <summary>
        ///   Creates  a new <see cref = " RelyingParty" />.
        /// </summary>
        /// <param name = "name">Name of this new <see cref = " RelyingParty" />.</param>
        /// <param name = "realm">Realm of the relying party.</param>
        /// <param name = "reply">ReplyTo address for the relying party. May be null.</param>
        /// <param name = "tokenType">The type of token that the relying party consumes.</param>
        /// <param name = "requireEncryption">Whether to require asymmetric token encryption.</param>
        /// <returns>The new <see cref = " RelyingParty" /> created.</returns>
        public static RelyingParty CreateRelyingParty(
            this ManagementService svc, string name, string realm, string reply, RelyingPartyTokenType tokenType, bool requireEncryption)
        {
            svc.DeleteRelyingPartyByRealmIfExists(realm);

            var relyingParty = new RelyingParty
            {
                AsymmetricTokenEncryptionRequired = requireEncryption, Name = name, TokenType = tokenType.ToString(), TokenLifetime = 3600,
            };

            svc.AddToRelyingParties(relyingParty);

            //
            // Create the Realm address
            //
            var realmAddress = new RelyingPartyAddress {
                Address = realm, EndpointType = RelyingPartyAddressType.Realm.ToString(),
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realmAddress);

            if (!string.IsNullOrEmpty(reply))
            {
                //
                // Create the ReplyTo address
                //
                var replyAddress = new RelyingPartyAddress {
                    Address = reply, EndpointType = RelyingPartyAddressType.Reply.ToString(),
                };

                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", replyAddress);
            }

            return(relyingParty);
        }
        /// <summary>
        /// Create a Facebook identity provider with associated keys and permissions configured.
        /// </summary>
        /// <param name="applicationId">The Facebook Application ID</param>
        /// <param name="applicationSecret">The Facebook Application Secret</param>
        /// <param name="applicationPermissions">The permissions to request from Facebook</param>
        /// <returns></returns>
        public static IdentityProvider CreateFacebookIdentityProvider(this ManagementService svc, string applicationId, string applicationSecret, string applicationPermissions)
        {
            string name = String.Format(CultureInfo.InvariantCulture, "Facebook-{0}", applicationId);

            Issuer issuer = new Issuer()
            {
                Name = name
            };

            svc.AddToIssuers(issuer);

            //
            // Create the Identity Provider
            //
            IdentityProvider identityProvider = new IdentityProvider()
            {
                DisplayName        = name,
                LoginParameters    = applicationPermissions,
                WebSSOProtocolType = IdentityProviderProtocolType.Facebook.ToString(),
            };

            svc.AddObject("IdentityProviders", identityProvider);
            svc.SetLink(identityProvider, "Issuer", issuer);

            //
            // Create the application Id and application secret keys for this facebook application.
            //
            IdentityProviderKey applicationIdKey = new IdentityProviderKey()
            {
                DisplayName = "Facebook application ID",
                Type        = IdentityProviderKeyType.ApplicationKey.ToString(),
                Usage       = IdentityProviderKeyUsage.ApplicationId.ToString(),
                Value       = Encoding.UTF8.GetBytes(applicationId),
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.MaxValue,
            };

            svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", applicationIdKey);

            IdentityProviderKey applicationSecretKey = new IdentityProviderKey()
            {
                DisplayName = "Facebook application Secret",
                Type        = IdentityProviderKeyType.ApplicationKey.ToString(),
                Usage       = IdentityProviderKeyUsage.ApplicationSecret.ToString(),
                Value       = Encoding.UTF8.GetBytes(applicationSecret),
                StartDate   = DateTime.UtcNow,
                EndDate     = DateTime.MaxValue,
            };

            svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", applicationSecretKey);

            identityProvider.Issuer = issuer;
            return(identityProvider);
        }
        /// <summary>
        /// Create a WS-Federation identity provider with associated keys and addresses.
        /// </summary>
        public static IdentityProvider CreateWsFederationIdentityProvider(this ManagementService svc, string name, byte[] signingCertificateValue, DateTime keyStartDate, DateTime keyEndDate, string signInUrl)
        {
            Issuer issuer = new Issuer()
            {
                Name = name
            };

            svc.AddToIssuers(issuer);

            //
            // Create the Identity Provider
            //
            IdentityProvider identityProvider = new IdentityProvider()
            {
                DisplayName        = name,
                WebSSOProtocolType = IdentityProviderProtocolType.WsFederation.ToString(),
            };

            svc.AddObject("IdentityProviders", identityProvider);

            svc.SetLink(identityProvider, "Issuer", issuer);

            //
            // Create the Identity Provider key used to validate the signature of IDP-signed tokens.
            //

            IdentityProviderKey signingKey = new IdentityProviderKey()
            {
                DisplayName = "SampleIdentityProviderKeyDisplayName",
                Type        = IdentityProviderKeyType.X509Certificate.ToString(),
                Usage       = IdentityProviderKeyUsage.Signing.ToString(),
                Value       = signingCertificateValue,
                StartDate   = keyStartDate.ToUniversalTime(),
                EndDate     = keyEndDate.ToUniversalTime()
            };

            svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", signingKey);

            // Create the sign-in address for Identity Provider
            IdentityProviderAddress signInAddress = new IdentityProviderAddress()
            {
                Address      = signInUrl,
                EndpointType = IdentityProviderEndpointType.SignIn.ToString(),
            };

            svc.AddRelatedObject(identityProvider, "IdentityProviderAddresses", signInAddress);

            identityProvider.Issuer = issuer;
            return(identityProvider);
        }
Пример #4
0
        public static RelyingParty AddRelyingParty(this ManagementService svc, Uri realm,
                                                   string relyingPartyName, DateTime startDate, DateTime endDate,
                                                   byte[] tokenSigningKey, int tokenLifetime)
        {
            Contract.Requires(svc != null);
            Contract.Requires(realm != null);
            Contract.Requires(realm.IsAbsoluteUri);
            Contract.Requires(realm.AbsolutePath == "/");
            Contract.Requires(!string.IsNullOrWhiteSpace(relyingPartyName));
            Contract.Requires(startDate != default(DateTime));
            Contract.Requires(endDate > startDate);
            Contract.Requires(tokenSigningKey != null);
            Contract.Requires(tokenLifetime >= 1);

            var relyingParty = new RelyingParty()
            {
                Name = relyingPartyName,
                AsymmetricTokenEncryptionRequired = false,
                TokenType     = "SWT",
                TokenLifetime = tokenLifetime
            };

            svc.AddToRelyingParties(relyingParty);

            var relyingPartyAddress = new RelyingPartyAddress()
            {
                Address      = realm.AbsoluteUri,
                EndpointType = "Realm"
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", relyingPartyAddress);

            var relyingPartyKey = new RelyingPartyKey()
            {
                StartDate = startDate,
                EndDate   = endDate,
                Type      = "Symmetric",
                Usage     = "Signing",
                IsPrimary = true,
                Value     = tokenSigningKey
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            svc.SaveChanges(SaveChangesOptions.Batch);

            return(relyingParty);
        }
Пример #5
0
        public static void AddIdentity(this ManagementService svc,
                                       Credentials serviceIdentity, DateTime startDate, DateTime endDate)
        {
            Contract.Requires(svc != null);
            Contract.Requires(serviceIdentity != null);
            Contract.Requires(startDate != default(DateTime));
            Contract.Requires(endDate > startDate);

            var sid = new ServiceIdentity()
            {
                Name = serviceIdentity.UserName
            };

            var key = new ServiceIdentityKey()
            {
                StartDate   = startDate,
                EndDate     = endDate,
                Type        = "Password",
                Usage       = "Password",
                Value       = Encoding.UTF8.GetBytes(serviceIdentity.Password),
                DisplayName = string.Format(CultureInfo.InvariantCulture,
                                            "{0} key for {1}", "Password", serviceIdentity.UserName)
            };

            svc.AddToServiceIdentities(sid);

            svc.AddRelatedObject(sid, "ServiceIdentityKeys", key);

            svc.SaveChanges(SaveChangesOptions.Batch);
        }
        private void LinkExistingRuleGroups(ManagementService client, Action <LogInfo> logAction)
        {
            foreach (var linkedRuleGroup in this.relyingPartySpec.LinkedRuleGroups())
            {
                var @group    = linkedRuleGroup;
                var ruleGroup = client.RuleGroups.Where(rg => rg.Name.Equals(group)).Single();

                var relyingParty = client.RelyingParties.Where(rp => rp.Name.Equals(this.relyingPartySpec.Name())).Single();

                var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                {
                    RuleGroupId  = ruleGroup.Id,
                    RelyingParty = relyingParty
                };

                this.LogMessage(logAction, string.Format("Linking Relying Party '{0}' to Rule Group '{1}'", this.relyingPartySpec.Name(), linkedRuleGroup));
                client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            }

            if (this.relyingPartySpec.LinkedRuleGroups().Any())
            {
                client.SaveChanges(SaveChangesOptions.Batch);
                this.LogSavingChangesMessage(logAction);
            }
        }
Пример #7
0
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            ManagementService client = CreateManagementServiceClient();
            var relyingParties       = client.RelyingParties;

            if (relyingParties != null)
            {
                foreach (var relyingParty in relyingParties)
                {
                    string name = relyingParty.Name;

                    if (name == RelyingParty)
                    {
                        RelyingPartyAddress address = new RelyingPartyAddress();
                        address.Address      = RelyingPartyRelayAddress;
                        address.EndpointType = "Reply";

                        client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", address);
                        client.SaveChanges(SaveChangesOptions.Batch);
                    }
                }
            }
            else
            {
                throw new Exception("Failed to get the Relying Parties list from the ACS Management Service.");
            }
        }
Пример #8
0
        public void Save()
        {
            ManagementService serviceClient = ManagementServiceHelper.CreateManagementServiceClient(this.settings);
            ServiceIdentity   serviceId     = serviceClient.GetServiceIdentityByName(this.Name);

            if (serviceId == null)
            {
                serviceId = serviceClient.CreateServiceIdentity(this.Name, Encoding.UTF8.GetBytes(this.Password), ServiceIdentityKeyType.Password,
                                                                ServiceIdentityKeyUsage.Password);

                ServiceIdentityKey key = new ServiceIdentityKey
                {
                    EndDate     = DateTime.MaxValue.AddDays(-1).ToUniversalTime(),
                    StartDate   = DateTime.UtcNow.ToUniversalTime(),
                    Type        = ServiceIdentityKeyType.Symmetric.ToString(),
                    Usage       = ServiceIdentityKeyUsage.Signing.ToString(),
                    Value       = this.Key,
                    DisplayName = String.Format(CultureInfo.InvariantCulture, "Symmetric key for {0}", this.Name)
                };
                serviceClient.AddRelatedObject(serviceId, "ServiceIdentityKeys", key);
            }
            else
            {
                if (serviceId.Description != this.Description)
                {
                    serviceId.Description = this.Description;
                    serviceClient.UpdateObject(serviceId);
                }
                serviceClient.UpdateServiceIdentityKey(this.Name, Encoding.UTF8.GetBytes(this.Password), ServiceIdentityKeyType.Password);
                serviceClient.UpdateServiceIdentityKey(this.Name, this.Key, ServiceIdentityKeyType.Symmetric);
            }
            serviceClient.SaveChanges(SaveChangesOptions.Batch);
        }
Пример #9
0
        /// <summary>
        /// Configures the ACS service namespace with the proper objects for this sample.
        /// </summary>
        /// <remarks>
        /// Existing objects that are needed for this sample will be deleted and recreated.
        /// </remarks>
        static void Main(string[] args)
        {
            const string rpName        = "ASPNET Simple MVC Sample";
            const string rpRealm       = "http://localhost:63000/";
            const string rpErrorUrl    = "http://localhost:63000/Error";
            const string ruleGroupName = "Default rule group for ASPNET Simple MVC Sample";

            const string googleIdpName = "Google";
            const string yahooIdpName  = "Yahoo!";

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            svc.DeleteRelyingPartyByRealmIfExists(rpRealm);
            svc.DeleteRuleGroupByNameIfExists(ruleGroupName);
            svc.DeleteIdentityProviderIfExists(googleIdpName);
            svc.DeleteIdentityProviderIfExists(yahooIdpName);
            svc.SaveChangesBatch();

            IdentityProvider live   = svc.GetIdentityProviderByName("uri:WindowsLiveID");
            IdentityProvider google = svc.CreateOpenIdIdentityProvider(googleIdpName, "https://www.google.com/accounts/o8/ud");
            IdentityProvider yahoo  = svc.CreateOpenIdIdentityProvider(yahooIdpName, "https://open.login.yahooapis.com/openid/op/auth");

            IdentityProvider[] associatedProviders = new[] { live, google, yahoo };

            //
            // Create the relying party. In this case, the Realm and the ReplyTo are the same address.
            //
            RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpRealm, RelyingPartyTokenType.SAML_2_0, false);

            svc.AssociateIdentityProvidersWithRelyingParties(associatedProviders, new[] { relyingParty });

            //
            // Configure the error URL.
            //
            RelyingPartyAddress errorUrl = new RelyingPartyAddress()
            {
                Address      = rpErrorUrl,
                EndpointType = RelyingPartyAddressType.Error.ToString()
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", errorUrl);

            RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            //
            // Create simple rules to pass through all claims from each issuer.
            //
            foreach (IdentityProvider identityProvider in associatedProviders)
            {
                string ruleDescription = String.Format(CultureInfo.InvariantCulture, "Pass through all claims from '{0}'", identityProvider.Issuer.Name);
                svc.CreateRule(identityProvider.Issuer, null, null, null, null, ruleGroup, ruleDescription);
            }
            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
Пример #10
0
        private static void LinkRuleGroupToRelyingParty(ManagementService client, RuleGroup ruleGroup, RelyingParty relyingParty)
        {
            Guard.NotNull(() => ruleGroup, ruleGroup);
            Guard.NotNull(() => relyingParty, relyingParty);

            var relyingPartyRuleGroup = new RelyingPartyRuleGroup
            {
                RuleGroupId  = ruleGroup.Id,
                RelyingParty = relyingParty
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            client.SaveChanges(SaveChangesOptions.Batch);
        }
Пример #11
0
        private static void AddEncryptionKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] encryptionCert, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Encryption Certificate for " + relyingPartyName,
                Type         = KeyType.X509Certificate.ToString(),
                Usage        = KeyUsage.Encrypting.ToString(),
                Value        = encryptionCert,
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
Пример #12
0
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] symmetricKey, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Signing Key for " + relyingPartyName,
                Type         = KeyType.Symmetric.ToString(),
                Usage        = KeyUsage.Signing.ToString(),
                Value        = symmetricKey,
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate,
                IsPrimary    = true
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
        /// <summary>
        /// Creates  a new ServiceIdentity and an associated key of the value, type, and usage specified.
        /// </summary>
        public static ServiceIdentity CreateServiceIdentity(this ManagementService svc, string name, byte[] keyValue, ServiceIdentityKeyType keyType, ServiceIdentityKeyUsage keyUsage)
        {
            ServiceIdentity sid = new ServiceIdentity()
            {
                Name = name
            };

            DateTime startDate, endDate;

            if (keyType == ServiceIdentityKeyType.X509Certificate)
            {
                //
                // ACS requires that the key start and end dates be within the certificate's validity period.
                //
                X509Certificate2 cert = new X509Certificate2(keyValue);

                startDate = cert.NotBefore.ToUniversalTime();
                endDate   = cert.NotAfter.ToUniversalTime();
            }
            else
            {
                startDate = DateTime.UtcNow;
                endDate   = DateTime.MaxValue;
            }

            ServiceIdentityKey key = new ServiceIdentityKey()
            {
                EndDate     = endDate.ToUniversalTime(),
                StartDate   = startDate.ToUniversalTime(),
                Type        = keyType.ToString(),
                Usage       = keyUsage.ToString(),
                Value       = keyValue,
                DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", keyType.ToString(), name)
            };

            svc.AddToServiceIdentities(sid);
            svc.AddRelatedObject(
                sid,
                "ServiceIdentityKeys",
                key);

            return(sid);
        }
Пример #14
0
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] signingCert, string signingCertPassword, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
            {
                DisplayName  = "Signing Certificate for " + relyingPartyName,
                Type         = KeyType.X509Certificate.ToString(),
                Usage        = KeyUsage.Signing.ToString(),
                Value        = signingCert,
                Password     = string.IsNullOrEmpty(signingCertPassword) ? null : new UTF8Encoding().GetBytes(signingCertPassword),
                RelyingParty = relyingParty,
                StartDate    = defaultStartDate,
                EndDate      = defaultEndDate,
                IsPrimary    = true
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
Пример #15
0
        /// <summary>
        /// Insert relying party encrypting keys.
        /// </summary>
        /// <param name="svc">Management service instance.</param>
        /// <param name="rpKeys">List of keys to insert.</param>
        /// <param name="relyingParty">Relying Party associated with the keys.</param>
        private static void InsertRelyingPartyEncryptingKeysFromMetadata(ManagementService svc, List <X509Certificate2> rpKeys, RelyingParty relyingParty)
        {
            foreach (X509Certificate2 certificate in rpKeys)
            {
                RelyingPartyKey keyFromMetadata = new RelyingPartyKey()
                {
                    Usage       = RelyingPartyKeyUsage.Encrypting.ToString(),
                    DisplayName = string.Format(CultureInfo.InvariantCulture, "{0} Encrypting Key", relyingParty.Name),
                    //
                    // As a security best practice, set the start and end dates on the data entry
                    // to be the same value as the dates on the certificate.
                    //
                    StartDate = certificate.NotBefore.ToUniversalTime(),
                    EndDate   = certificate.NotAfter.ToUniversalTime(),
                    Type      = RelyingPartyKeyType.X509Certificate.ToString(),
                    Value     = certificate.GetRawCertData()
                };

                Console.WriteLine(String.Format("Adding new relying party key with subject: '{0}'.\n", GetSubjectFromCertificate(keyFromMetadata.Value)));
                svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", keyFromMetadata);
            }
        }
Пример #16
0
        /// <summary>
        /// Insert keys for an identity provider.
        /// </summary>
        /// <param name="svc">ManagementService instance.</param>
        /// <param name="idpKeys">List of keys to insert.</param>
        /// <param name="identityProvider">Identity Provider associated with the keys.</param>
        private static void InsertIdentityProviderSigningKeysFromMetadata(ManagementService svc, List <X509Certificate2> idpKeys, IdentityProvider identityProvider)
        {
            foreach (X509Certificate2 certificate in idpKeys)
            {
                IdentityProviderKey keyFromMetadata = new IdentityProviderKey()
                {
                    Usage       = IdentityProviderKeyUsage.Signing.ToString(),
                    DisplayName = string.Format(CultureInfo.InvariantCulture, "{0} Signing Key", identityProvider.DisplayName),
                    //
                    // As a security best practice, set the start and end dates on the data entry
                    // to be the same value as the dates on the certificate.
                    //
                    StartDate = certificate.NotBefore.ToUniversalTime(),
                    EndDate   = certificate.NotAfter.ToUniversalTime(),
                    Type      = IdentityProviderKeyType.X509Certificate.ToString(),
                    Value     = certificate.GetRawCertData()
                };

                Console.WriteLine(String.Format("Adding new identity provider key with subject: '{0}'.", GetSubjectFromCertificate(keyFromMetadata.Value)));
                svc.AddRelatedObject(identityProvider, "IdentityProviderKeys", keyFromMetadata);
            }
        }
        /// <summary>
        /// Generate a symmetric RelyingPartyKey and associcate it with the given relying party.
        /// </summary>
        public static RelyingPartyKey GenerateRelyingPartySymmetricKey(this ManagementService svc, RelyingParty relyingParty, DateTime startDate, DateTime endDate, bool isPrimary)
        {
            //
            // Symmetric keys used by ACS are 256-bits, which equals 32 bytes.
            //
            byte[] keyValue = new byte[32];
            new RNGCryptoServiceProvider().GetBytes(keyValue);

            RelyingPartyKey relyingPartyKey = new RelyingPartyKey()
            {
                DisplayName = String.Format(CultureInfo.InvariantCulture, "Default signing key for {0}", relyingParty.Name),
                EndDate     = endDate.ToUniversalTime(),
                IsPrimary   = isPrimary,
                StartDate   = startDate.ToUniversalTime(),
                Type        = RelyingPartyKeyType.Symmetric.ToString(),
                Usage       = RelyingPartyKeyUsage.Signing.ToString(),
                Value       = keyValue
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            return(relyingPartyKey);
        }
        /// <summary>
        /// Create a RelyingPartyKey with the given value, type, and usage, and associate it with the given relying party.
        /// </summary>
        public static RelyingPartyKey CreateRelyingPartyKey(this ManagementService svc, RelyingParty relyingParty, byte[] keyValue, string password, RelyingPartyKeyType keyType, RelyingPartyKeyUsage keyUsage, bool isPrimary)
        {
            DateTime startDate, endDate;


            if (keyType == RelyingPartyKeyType.X509Certificate)
            {
                //
                // ACS requires that the key start and end dates be within the certificate's validity period.
                //
                X509Certificate2 cert = new X509Certificate2(keyValue, password);

                startDate = cert.NotBefore.ToUniversalTime();
                endDate   = cert.NotAfter.ToUniversalTime();
            }
            else
            {
                startDate = DateTime.UtcNow;
                endDate   = DateTime.MaxValue;
            }

            RelyingPartyKey relyingPartyKey = new RelyingPartyKey()
            {
                DisplayName = String.Format(CultureInfo.InvariantCulture, "Default {0} key for {1}", keyType, relyingParty.Name),
                EndDate     = endDate,
                IsPrimary   = isPrimary,
                Password    = string.IsNullOrEmpty(password) ? null : Encoding.UTF8.GetBytes(password),
                StartDate   = startDate,
                Type        = keyType.ToString(),
                Usage       = keyUsage.ToString(),
                Value       = keyValue,
            };

            svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            return(relyingPartyKey);
        }
        /// <summary>
        /// Create an OpenID identity provider with the associated sign-in address
        /// </summary>
        /// <param name="name">The name of the issuer to create.</param>
        /// <param name="signInUrl">The post-discovery OpenID endpoint URL of the provider.</param>
        /// <returns>The created identity provider.</returns>
        public static IdentityProvider CreateOpenIdIdentityProvider(this ManagementService svc, string name, string signInUrl)
        {
            Issuer issuer = new Issuer()
            {
                Name = name
            };

            svc.AddToIssuers(issuer);

            //
            // Create the Identity Provider
            //
            IdentityProvider identityProvider = new IdentityProvider()
            {
                DisplayName        = name,
                WebSSOProtocolType = IdentityProviderProtocolType.OpenId.ToString(),
            };

            svc.AddObject("IdentityProviders", identityProvider);

            svc.SetLink(identityProvider, "Issuer", issuer);

            //
            // Create the sign-in address for Identity Provider
            //
            IdentityProviderAddress signInAddress = new IdentityProviderAddress()
            {
                Address      = signInUrl,
                EndpointType = IdentityProviderEndpointType.SignIn.ToString(),
            };

            svc.AddRelatedObject(identityProvider, "IdentityProviderAddresses", signInAddress);

            identityProvider.Issuer = issuer;
            return(identityProvider);
        }
Пример #20
0
        private static void CreateRelyingParty(ManagementService client, string relyingPartyName, string ruleGroupName, string realmAddress, string replyAddress, TokenType tokenType, int tokenLifetime, bool asymmetricTokenEncryptionRequired, out RelyingParty relyingParty)
        {
            // Create Relying Party
            relyingParty = new RelyingParty
            {
                Name          = relyingPartyName,
                DisplayName   = relyingPartyName,
                Description   = relyingPartyName,
                TokenType     = tokenType.ToString(),
                TokenLifetime = tokenLifetime,
                AsymmetricTokenEncryptionRequired = asymmetricTokenEncryptionRequired
            };

            client.AddObject("RelyingParties", relyingParty);
            client.SaveChanges();

            if (!string.IsNullOrWhiteSpace(ruleGroupName))
            {
                RuleGroup ruleGroup = client.RuleGroups.Where(rg => rg.Name.Equals(ruleGroupName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (ruleGroup == null)
                {
                    ruleGroup = new RuleGroup
                    {
                        Name = ruleGroupName
                    };

                    client.AddToRuleGroups(ruleGroup);
                    client.SaveChanges();
                }

                var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                {
                    RuleGroupId  = ruleGroup.Id,
                    RelyingParty = relyingParty
                };

                client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            }

            // Create the Realm for Relying Party
            var realm = new RelyingPartyAddress
            {
                Address      = realmAddress,
                EndpointType = RelyingPartyAddressEndpointType.Realm.ToString(),
                RelyingParty = relyingParty
            };

            client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realm);

            if (!string.IsNullOrEmpty(replyAddress))
            {
                var reply = new RelyingPartyAddress
                {
                    Address      = replyAddress,
                    EndpointType = RelyingPartyAddressEndpointType.Reply.ToString(),
                    RelyingParty = relyingParty
                };

                client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", reply);
            }

            client.SaveChanges(SaveChangesOptions.Batch);
        }
Пример #21
0
        /// <summary>
        /// Add an Identity Provider
        /// </summary>
        private static Issuer CreateIdpManually(DateTime startDate, DateTime endDate, ManagementService svc0, string idpName, string idpDisplayName, string idpAddress, string idpKeyDisplayName)
        {
            var issuer = new Issuer
            {
                Name = idpName
            };

            // Check the Issuer does not exist previouly (if it exists, delete it)
            var oldIssuer = svc0.Issuers.Where(ip => ip.Name == issuer.Name).FirstOrDefault();

            if (oldIssuer != null)
            {
                svc0.DeleteObject(oldIssuer);
                svc0.SaveChanges();
            }

            // Add Issuer
            svc0.AddToIssuers(issuer);
            svc0.SaveChanges(SaveChangesOptions.Batch);
            Console.WriteLine("Info: Issuer created: {0}", idpName);

            var idp = new IdentityProvider
            {
                DisplayName        = idpDisplayName,
                LoginLinkName      = idpDisplayName,
                WebSSOProtocolType = "WsFederation",
                IssuerId           = issuer.Id
            };

            // Check the IP does not exist previouly (if it exists, delete it)
            var oldIdentityProvider = svc0.IdentityProviders.Where(ip => ip.DisplayName == idp.DisplayName).FirstOrDefault();

            if (oldIdentityProvider != null)
            {
                svc0.DeleteObject(oldIdentityProvider);
                svc0.SaveChanges();
            }

            // Add the new IP to ACS
            svc0.AddObject("IdentityProviders", idp);

            // Console.WriteLine("Info: Identity Provider created: {0}", idp.Name);
            Console.WriteLine("Info: Identity Provider created: {0}", idp.DisplayName);

            // Identity provider public key to verify the signature
            var cert = File.ReadAllBytes(@"Resources\SelfSTS.cer");
            var key  = new IdentityProviderKey
            {
                IdentityProvider = idp,
                DisplayName      = idpKeyDisplayName,
                EndDate          = endDate,
                StartDate        = startDate,
                Type             = "X509Certificate",
                Usage            = "Signing",
                Value            = cert
            };

            svc0.AddRelatedObject(idp, "IdentityProviderKeys", key);
            svc0.SaveChanges(SaveChangesOptions.Batch);

            Console.WriteLine("Info: Identity Provider Key added: {0}", idpKeyDisplayName);

            // WS-Federation sign-in URL
            var idpaSignIn = new IdentityProviderAddress
            {
                IdentityProviderId = idp.Id,
                EndpointType       = "SignIn",
                Address            = idpAddress
            };

            svc0.AddRelatedObject(idp, "IdentityProviderAddresses", idpaSignIn);
            svc0.SaveChanges(SaveChangesOptions.Batch);

            Console.WriteLine("Info: Identity Provider Address added: {0}", idpAddress);

            string labRelyingPartyName = "WebSiteAdvancedACS";

            // Relying Party related to the Identity Provider
            foreach (var existingRelyingParty in svc0.RelyingParties)
            {
                var rpid = new RelyingPartyIdentityProvider
                {
                    IdentityProviderId = idp.Id,
                    RelyingPartyId     = existingRelyingParty.Id
                };
                existingRelyingParty.RelyingPartyIdentityProviders.Add(rpid);
                idp.RelyingPartyIdentityProviders.Add(rpid);
                svc0.AddToRelyingPartyIdentityProviders(rpid);
            }

            svc0.SaveChanges(SaveChangesOptions.Batch);

            Console.WriteLine("Info: Relying Party added to Identity Provider: {0}", labRelyingPartyName);

            return(issuer);
        }
Пример #22
0
        /// <summary>
        /// Add the Rules into a Rule Group.
        /// </summary>
        private static void AddRulesToRuleGroup(string ruleGroupName, string issuerName)
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            RuleGroup rg = svc.RuleGroups.AddQueryOption("$filter", "Name eq '" + ruleGroupName + "'").FirstOrDefault();

            Issuer issuer = svc.Issuers.Where(i => i.Name == issuerName).ToArray()[0];

            Rule namePassthroughRule = new Rule()
            {
                Issuer   = issuer,
                IssuerId = issuer.Id,

                // InputClaimIssuerId = issuer.Id,
                InputClaimType  = "http://www.theselfsts2.net/claims/nome",
                OutputClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                RuleGroup       = rg,
                Description     = "Passthrough \"nome\" claim from SelfSTS2 as \"name\""
            };

            svc.AddRelatedObject(rg, "Rules", namePassthroughRule);

            Rule emailPassthroughRule = new Rule()
            {
                Issuer          = issuer,
                IssuerId        = issuer.Id,
                InputClaimType  = "http://www.theselfsts2.net/claims/postaelettronica",
                OutputClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
                RuleGroup       = rg,
                Description     = "Passthrough \"postaelettronica\" claim from SelfSTS2 as \"emailaddress\""
            };

            svc.AddRelatedObject(rg, "Rules", emailPassthroughRule);

            Rule goldenRule = new Rule()
            {
                Issuer           = issuer,
                IssuerId         = issuer.Id,
                InputClaimType   = "http://www.theselfsts2.net/claims/gruppo",
                InputClaimValue  = "Amministratori",
                OutputClaimType  = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role",
                OutputClaimValue = "Gold",
                RuleGroup        = rg,
                Description      = "Map Gold Role SelfSTS2"
            };

            svc.AddRelatedObject(rg, "Rules", goldenRule);

            Rule silverRule = new Rule()
            {
                Issuer           = issuer,
                IssuerId         = issuer.Id,
                InputClaimType   = "http://www.theselfsts2.net/claims/gruppo",
                InputClaimValue  = "Utenti",
                OutputClaimType  = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role",
                OutputClaimValue = "Silver",
                RuleGroup        = rg,
                Description      = "Map Silver Role SelfSTS2"
            };

            svc.AddRelatedObject(rg, "Rules", silverRule);

            svc.SaveChanges(SaveChangesOptions.Batch);

            Console.WriteLine();
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Info: Passthrough Rules:");
            Console.WriteLine("Info: Passthrough Name Rule created: {0}", namePassthroughRule.Description);
            Console.WriteLine("Info: Passthrough Email Rule created: {0}", emailPassthroughRule.Description);

            Console.WriteLine();
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Info: Roles Rules:");
            Console.WriteLine("Info: Golden Rule created: {0}", goldenRule.Description);
            Console.WriteLine("Info: Silver Rule created: {0}", silverRule.Description);
        }