/// <summary>
        /// Replace the IdentityProvider signing keys with a new set of keys from a metadata update.
        /// </summary>
        static void UpdateIdentityProviderMetadata()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            Console.WriteLine(String.Format("Reading metadata from file '{0}'...\n", IDPMetadataForUpdate));
            using (FileStream fileStream = new FileStream(IDPMetadataForUpdate, FileMode.Open))
            {
                //
                // Note that this sample uses EntityID to correlate between the identity provider originally imported
                // and the identity provider to update.
                //
                EntityDescriptor        metadata  = ReadMetadata(fileStream);
                List <X509Certificate2> idpKeys   = ExtractX509CertificatesFromMetadata <SecurityTokenServiceDescriptor>(metadata, KeyType.Signing);
                string           issuerName       = GetEntityName(metadata);
                IdentityProvider identityProvider = svc.GetIdentityProviderByName(issuerName, true);

                Console.WriteLine(String.Format("Updating metadata for issuer '{0}'...\n", issuerName));

                //
                // For the sake of simplicity, the existing keys are simply deleted and new ones added.
                // Metadata contains more information such as endpoint addresses, claim types issued, etc.
                // Updating the remainder of these attributes is left as an exercise to the reader.
                //
                DeleteExistingIdentityProviderSigningKeys(svc, identityProvider);
                InsertIdentityProviderSigningKeysFromMetadata(svc, idpKeys, identityProvider);

                //
                // SaveChangesOptions.Batch guarantees a transaction across all operations prior to this call. This
                // is important because on a running service, the update must happen atomically or service calls may fail.
                //
                svc.SaveChangesBatch();
            }
        }
        static void Main(string[] args)
        {
            //
            // Create a SAML token signed with the given certificate
            //
            byte[]             clientCertificateBytes = ManagementServiceHelper.ReadBytesFromPfxFile(ClientCertificateFilePath, ClientCertificatePassword);
            Saml2SecurityToken token = SelfSignedSaml2TokenGenerator.GetSamlAssertionSignedWithCertificate(ClientName, clientCertificateBytes, ClientCertificatePassword);

            //
            // Encode the SAML token into an OAuth request to ACS.
            //
            Dictionary <string, string> requestParameters = new Dictionary <string, string>();

            requestParameters[OAuth2Constants.Scope]     = ConfigurationManager.AppSettings.Get("RelyingPartyScope");
            requestParameters[OAuth2Constants.GrantType] = WifTokenTypes.Saml2TokenProfile11;
            requestParameters[OAuth2Constants.Assertion] = GetSaml2TokenString(token);

            Dictionary <string, string> acsResponse = GetOAuth2ResponseFromAcs(requestParameters);

            //
            // Pass the access token returned by ACS to the protected resource.
            //
            Console.WriteLine(GetProtectedResource(acsResponse[OAuth2Constants.AccessToken]));

            Console.WriteLine("Press <ENTER> to exit...");
            Console.ReadLine();
        }
        /// <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            = "Federation Sample RP";
            const string rpRealm           = "http://*****:*****@"..\..\..\Certificates\ACS2SigningCertificate.pfx", "password");
            byte[] decryptionCertificate = ManagementServiceHelper.ReadBytesFromPfxFile(@"..\..\..\Certificates\ACS2DecryptionCert.pfx", "password");
            byte[] encryptionCertificate = new X509Certificate2(@"..\..\..\Certificates\WcfServiceCertificate.cer").RawData;

            svc.CreateRelyingPartyKey(relyingParty, signingCertificate, "password", RelyingPartyKeyType.X509Certificate, RelyingPartyKeyUsage.Signing, true);
            svc.CreateRelyingPartyKey(relyingParty, encryptionCertificate, null, RelyingPartyKeyType.X509Certificate, RelyingPartyKeyUsage.Encrypting, true);

            svc.CreateIdentityProviderDecryptionKey(decryptionKeyName, decryptionCertificate, "password", true);

            svc.ImportIdentityProviderFromMetadataUrl(new Uri(IdentityProviderMetadataUrl));

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

            RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName);

            svc.GenerateRules(ruleGroup, new[] { svc.GetIdentityProviderByName(entityId) });
            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
        /// <summary>
        /// Replace the RelyingParty encryption keys with a new set of keys from a metadata update.
        /// </summary>
        static void UpdateRelyingPartyMetadata()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            Console.WriteLine(String.Format("Reading metadata from file '{0}'...\n", RPMetadataForUpdate));
            using (FileStream fileStream = new FileStream(RPMetadataForUpdate, FileMode.Open))
            {
                //
                // Note that this sample uses EntityID to correlate between the relying party originally imported
                // and the relying party to update.
                //
                EntityDescriptor        metadata = ReadMetadata(fileStream);
                List <X509Certificate2> rpKeys   = ExtractX509CertificatesFromMetadata <ApplicationServiceDescriptor>(metadata, KeyType.Encryption);
                string       relyingPartyName    = GetEntityName(metadata);
                RelyingParty relyingParty        = svc.GetRelyingPartyByName(relyingPartyName, true);

                Console.WriteLine(String.Format("Updating metadata for relying party '{0}'...\n", relyingPartyName));

                //
                // For the purposes of this sample, the existing keys are simply deleted and new ones added.
                // Metadata contains more information such as endpoint addresses.
                // Updating the remainder of these attributes is left as an exercise to the reader.
                //
                DeleteExistingRelyingPartyEncryptingKeys(svc, relyingParty);
                InsertRelyingPartyEncryptingKeysFromMetadata(svc, rpKeys, relyingParty);

                //
                // SaveChangesOptions.Batch guarantees a transaction across all operations prior to this call. This
                // is important because on a running service, the update must happen atomically or service calls may fail.
                //
                svc.SaveChangesBatch();
            }
        }
Esempio n. 5
0
        private ManagementService GetAccessControlManagementService(string ns, string acs, string acsSecret)
        {
            var acsConfig   = new AccessControlConfiguration(ns, acs, acsSecret);
            var mgmtService = new ManagementServiceHelper(acsConfig);

            return(mgmtService.CreateManagementServiceClient());
        }
        /// <summary>
        /// CRUD for service key of 'X509Certificate' key type.
        /// </summary>
        private static void CertificateServiceKeyCRUD()
        {
            string displayName = "Certificate for signing tokens to RPs";

            // Add a signing certificate.
            {
                string pfxFileName        = "SampleCert.pfx";
                string protectionPassword = @"pass@word1";

                byte[] signingCertificate = ManagementServiceHelper.ReadBytesFromPfxFile(pfxFileName, protectionPassword);

                EnumerateServiceKeys();

                DeleteServiceKeyByDisplayNameIfExists(displayName);
                EnumerateServiceKeys();

                AddServiceKey(displayName, signingCertificate, protectionPassword, ServiceKeyType.X509Certificate, ServiceKeyUsage.Signing);
                EnumerateServiceKeys();
            }

            // Update and delete the signing certificate.
            {
                string pfxFileName2        = "TenantSigningCert.pfx";
                string protectionPassword2 = @"TenantSigningCert";

                byte[] updatedSigningCertificate = ManagementServiceHelper.ReadBytesFromPfxFile(pfxFileName2, protectionPassword2);

                UpdateServiceKey(displayName, updatedSigningCertificate, protectionPassword2, ServiceKeyType.X509Certificate);
                EnumerateServiceKeys();

                DeleteServiceKeyByDisplayNameIfExists(displayName);
                EnumerateServiceKeys();
            }
        }
        /// <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();
        }
        static void DeleteServiceIdentity(string name)
        {
            AccessControlSettings settings      = new AccessControlSettings(@namespace, managementKey);
            ManagementService     serviceClient = ManagementServiceHelper.CreateManagementServiceClient(settings);

            serviceClient.DeleteServiceIdentityIfExists(name);
            serviceClient.SaveChanges();
            Console.WriteLine("Deleted.");
        }
        static void Main(string[] args)
        {
            const string RPRealm       = "http://ContosoContacts/";
            const string RPName        = "ContosoContacts";
            const string RuleGroupName = "Default rule group for ContosoContacts";

            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();

            //
            // Create Google and Yahoo! as identity providers. LiveID is already configured.
            //
            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 and its associated key.
            //
            RelyingParty relyingParty = svc.CreateRelyingParty(RPName, RPRealm, null, RelyingPartyTokenType.SWT, false);

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

            RelyingPartyKey relyingPartyKey = svc.GenerateRelyingPartySymmetricKey(relyingParty, DateTime.UtcNow, DateTime.MaxValue, true);

            Console.WriteLine("Generated symmetric key: {0}", Convert.ToBase64String(relyingPartyKey.Value));

            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 configured successfully. Press <ENTER> to exit...");
            Console.ReadLine();
        }
        /// <summary>
        /// Update the service key value and the protection password.
        /// </summary>
        private static void UpdateServiceKey(string displayName, byte[] keyValue, string protectionPassword, ServiceKeyType keyType)
        {
            UTF8Encoding      enc = new UTF8Encoding();
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            ServiceKey serviceKey = svc.ServiceKeys.Where(sk => sk.DisplayName == displayName && sk.Type == keyType.ToString()).First();

            serviceKey.Value    = keyValue;
            serviceKey.Password = string.IsNullOrEmpty(protectionPassword) ? null : enc.GetBytes(protectionPassword);

            svc.UpdateObject(serviceKey);
            svc.SaveChangesBatch();
        }
Esempio n. 11
0
        private static void CreateIdentityProviderWithRules()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            // Create Identity Provider
            var issuer = CreateIdpManually(DateTime.UtcNow, DateTime.UtcNow.AddYears(1), svc, "SelfSTS2", "SelfSTS2", "http://localhost:9000/STS/Issue/", "IdentityTKStsCertForSigning");

            // Add the Rules
            string ruleGroupname = "Default Rule Group for WebSiteAdvancedACS";

            AddRulesToRuleGroup(ruleGroupname, issuer.Name);

            Console.WriteLine("Done!");
        }
        /// <summary>
        /// Enumerate all service keys.
        /// </summary>
        private static void EnumerateServiceKeys()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            Console.WriteLine("Service Keys:\n");

            foreach (ServiceKey key in svc.ServiceKeys)
            {
                Console.WriteLine("Name     : " + key.DisplayName);
                Console.WriteLine("Type     : " + key.Type);
                Console.WriteLine("Password : "******"" : Encoding.UTF8.GetString(key.Password)));
                Console.WriteLine("Usage    : " + key.Usage);
                Console.WriteLine("Key      : " + Convert.ToBase64String(key.Value) + "\n");
            }
        }
        /// <summary>
        /// Delete a service key by its display name.
        /// </summary>
        private static void DeleteServiceKeyByDisplayNameIfExists(string displayName)
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            IQueryable <ServiceKey> serviceKeys = svc.ServiceKeys.Where(e => e.DisplayName == displayName);

            if (serviceKeys.Count() != 0)
            {
                foreach (ServiceKey sk in serviceKeys)
                {
                    svc.DeleteObject(sk);
                }

                svc.SaveChangesBatch();
            }
        }
        static void GetServiceIdentity(string name)
        {
            AccessControlSettings settings      = new AccessControlSettings(@namespace, managementKey);
            ManagementService     serviceClient = ManagementServiceHelper.CreateManagementServiceClient(settings);
            ServiceIdentity       si            = serviceClient.GetServiceIdentityByName(name);

            if (si != null)
            {
                ServiceIdentityKey symmKey =
                    (from sk in si.ServiceIdentityKeys where sk.Type == ServiceIdentityKeyType.Symmetric.ToString() select sk).FirstOrDefault();
                if (symmKey != null)
                {
                    Console.WriteLine("Name: {0}\nKey: {1}", si.Name, Convert.ToBase64String(symmKey.Value));
                    return;
                }
            }
            Console.Error.WriteLine("Service identity '{0}' not found or key not found", name);
        }
        /// <summary>
        /// Import the relying party from metadata using a call to the management service.
        /// </summary>
        static void ImportRelyingPartyMetadata()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            Console.WriteLine(String.Format("Reading metadata from file '{0}'...\n", RPMetadataForImport));
            using (FileStream fileStream = new FileStream(RPMetadataForImport, FileMode.Open))
            {
                EntityDescriptor metadata         = ReadMetadata(fileStream);
                string           relyingPartyName = GetEntityName(metadata);
                svc.DeleteRelyingPartyByNameIfExists(relyingPartyName);
                svc.SaveChangesBatch();

                // Import the relying party from metadata.
                Console.WriteLine(String.Format("Importing metadata for relying party '{0}'...\n", relyingPartyName));
                fileStream.Seek(0, SeekOrigin.Begin);
                svc.ImportRelyingPartyFromStream(fileStream);
            }
        }
        /// <summary>
        /// Import the identity provider from metadata using a call to the management service.
        /// </summary>
        static void ImportIdentityProviderMetadata()
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            Console.WriteLine(String.Format("Reading metadata from file '{0}'...\n", IDPMetadataForImport));
            using (FileStream fileStream = new FileStream(IDPMetadataForImport, FileMode.Open))
            {
                EntityDescriptor metadata   = ReadMetadata(fileStream);
                string           issuerName = GetEntityName(metadata);
                svc.DeleteIdentityProviderIfExists(issuerName);
                svc.SaveChangesBatch();

                // Import the identity provider from metadata.
                Console.WriteLine(String.Format("Importing metadata for issuer '{0}'...\n", issuerName));
                fileStream.Seek(0, SeekOrigin.Begin);
                svc.ImportIdentityProviderFromStream(fileStream);
            }
        }
        /// <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              = "Certificate Binding Sample RP";
            const string rpRealm             = "http://*****:*****@"..\..\..\Certificates\ACS2SigningCertificate.pfx", "password");
            byte[] encryptionCertificate = new X509Certificate2(@"..\..\..\Certificates\WcfServiceCertificate.cer").RawData;

            svc.CreateRelyingPartyKey(relyingParty, signingCertificate, "password", RelyingPartyKeyType.X509Certificate, RelyingPartyKeyUsage.Signing, true);
            svc.CreateRelyingPartyKey(relyingParty, encryptionCertificate, null, RelyingPartyKeyType.X509Certificate, RelyingPartyKeyUsage.Encrypting, true);

            byte[] clientCertificate = new X509Certificate2(@"..\..\..\Certificates\ACS2ClientCertificate.cer").RawData;

            svc.CreateServiceIdentity(serviceIdentityName, clientCertificate, ServiceIdentityKeyType.X509Certificate, ServiceIdentityKeyUsage.Signing);

            RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            //
            // Add a rule to pass through all ACS-issued claims.  These are represented by an issuer called "LOCAL AUTHORITY"
            // Null input and output claim types and values mean to pass-through all.
            //
            svc.CreateRule(svc.GetIssuerByName("LOCAL AUTHORITY"), null, null, null, null, ruleGroup, "Pass through all claims issued by ACS.");
            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
        /// <summary>
        /// Add a service key.
        /// </summary>
        private static void AddServiceKey(string displayName, byte[] keyValue, string protectionPassword, ServiceKeyType keyType, ServiceKeyUsage keyUsage)
        {
            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            UTF8Encoding enc = new UTF8Encoding();

            ServiceKey serviceKey = new ServiceKey()
            {
                DisplayName = displayName,
                Type        = keyType.ToString(),
                Usage       = keyUsage.ToString(),
                Value       = keyValue,
                Password    = string.IsNullOrEmpty(protectionPassword) ? null : enc.GetBytes(protectionPassword),
                StartDate   = defaultStartTime,
                EndDate     = defaultEndTime
            };

            svc.AddToServiceKeys(serviceKey);
            svc.SaveChangesBatch();
        }
        static void Main(string[] args)
        {
            const string ClientName    = "OAuth2SampleX509Identity";
            const string RPRealm       = "https://oauth2RelyingParty/";
            const string RPName        = "OAuth2 RP";
            const string RuleGroupName = "Default rule group for OAuth2 RP";

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            svc.DeleteServiceIdentityIfExists(ClientName);
            svc.DeleteRelyingPartyByRealmIfExists(RPRealm);
            svc.DeleteRuleGroupByNameIfExists(RuleGroupName);

            svc.SaveChangesBatch();

            X509Certificate2 clientCertificate = new X509Certificate2(@"..\..\..\Certificates\ACS2ClientCertificate.cer");

            svc.CreateServiceIdentity(ClientName, clientCertificate.RawData, ServiceIdentityKeyType.X509Certificate, ServiceIdentityKeyUsage.Signing);

            RelyingParty    relyingParty    = svc.CreateRelyingParty(RPName, RPRealm, null, RelyingPartyTokenType.SWT, false);
            RelyingPartyKey relyingPartyKey = svc.GenerateRelyingPartySymmetricKey(relyingParty, DateTime.UtcNow, DateTime.MaxValue, true);

            Console.WriteLine("Generated symmetric key: {0}", Convert.ToBase64String(relyingPartyKey.Value));

            Issuer    localAuthority = svc.GetIssuerByName("LOCAL AUTHORITY");
            RuleGroup ruleGroup      = svc.CreateRuleGroup(RuleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            svc.CreateRule(localAuthority, null, null, null, null, ruleGroup, "Pass through claims issued by ACS");

            svc.SaveChangesBatch();

            Console.WriteLine("Sample configured successfully. Press <ENTER> to exit...");
            Console.ReadLine();
        }
        /// <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 Service";
            const string rpRealm                 = "http://localhost:8000/Service/";
            const string serviceIdentityName     = "acssample";
            const string serviceIdentityPassword = "******";
            const string ruleGroupName           = "Default rule group for ASPNET Simple Service";

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            svc.DeleteRelyingPartyByRealmIfExists(rpRealm);
            svc.DeleteServiceIdentityIfExists(serviceIdentityName);
            svc.DeleteRuleGroupByNameIfExists(ruleGroupName);
            svc.SaveChangesBatch();

            RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpRealm, RelyingPartyTokenType.SWT, false);

            RelyingPartyKey relyingPartyKey = svc.GenerateRelyingPartySymmetricKey(relyingParty, DateTime.UtcNow, DateTime.UtcNow.AddYears(1), true);

            Console.WriteLine("Generated symmetric key value: {0}", Convert.ToBase64String(relyingPartyKey.Value));

            svc.CreateServiceIdentity(serviceIdentityName, Encoding.UTF8.GetBytes(serviceIdentityPassword), ServiceIdentityKeyType.Password, ServiceIdentityKeyUsage.Password);

            RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName);

            svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty);

            //
            // Add a rule to issue the "action=reverse" claim.
            //
            svc.CreateRule(svc.GetIssuerByName("LOCAL AUTHORITY"), null, null, "action", "reverse", ruleGroup, "Issue action=reverse claim.");
            svc.SaveChangesBatch();

            Console.WriteLine("Sample successfully configured. Press ENTER to continue ...");
            Console.ReadLine();
        }
        /// <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 MVC3 Custom Sign-In Page Sample";
            const string rpRealm   = "http://localhost:64000/";
            const string rpReplyTo = "http://localhost:64000/Account/SignIn";

            const string facebookName = "Facebook";
            const string yahooName    = "Yahoo!";

            const string defaultRuleGroupName = "Default rule group for ASPNET MVC3 Custom Sign-In Page Sample";

            // Please update these with your own Facebook application information
            const string applicationId     = "applicationid";
            const string applicationSecret = "applicationsecret";

            string facebookIdpName = String.Format(CultureInfo.InvariantCulture, "Facebook-{0}", applicationId);

            ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient();

            //
            // Clean up pre-existing configuration
            //
            svc.DeleteRelyingPartyByRealmIfExists(rpRealm);
            svc.DeleteRuleGroupByNameIfExists(defaultRuleGroupName);
            svc.DeleteIdentityProviderIfExists(facebookIdpName);
            svc.DeleteIdentityProviderIfExists(yahooName);
            svc.SaveChangesBatch();

            //
            // Create Identity Providers
            //
            IdentityProvider live = svc.GetIdentityProviderByName("uri:WindowsLiveID");;

            IdentityProvider facebook = svc.CreateFacebookIdentityProvider(applicationId, applicationSecret, "email,user_events");

            SetSignInInformation(svc, facebook, facebookName);

            IdentityProvider yahoo = svc.CreateOpenIdIdentityProvider(yahooName, "https://open.login.yahooapis.com/openid/op/auth");

            SetSignInInformation(svc, yahoo, yahooName);

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

            //
            // Create Relying Party
            //
            RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpReplyTo, RelyingPartyTokenType.SAML_2_0, false);

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

            RuleGroup ruleGroup = svc.CreateRuleGroup(defaultRuleGroupName);

            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();
        }
Esempio n. 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);
        }