コード例 #1
0
        private static IServicePrincipal CreateServicePrincipalWithRoleForApplicationAndExportToFile(
            Azure.IAuthenticated authenticated,
            IActiveDirectoryApplication activeDirectoryApplication,
            BuiltInRole role,
            string subscriptionId,
            string authFilePath)
        {
            Utilities.Log("Creating Service Principal...");
            string name = SdkContext.RandomResourceName("sp-sample", 20);
            //create a self-sighed certificate
            string      domainName   = name + ".com";
            string      certPassword = Utilities.CreatePassword();
            Certificate certificate  = Certificate.CreateSelfSigned(domainName, certPassword);

            // create  a Service Principal and assign it to a subscription with the role Contributor
            return(authenticated.ServicePrincipals
                   .Define("name")
                   .WithExistingApplication(activeDirectoryApplication)
                   // password credentials definition
                   .DefinePasswordCredential("ServicePrincipalAzureSample")
                   .WithPasswordValue(Utilities.CreatePassword())
                   .Attach()
                   // certificate credentials definition
                   .DefineCertificateCredential("spcert")
                   .WithAsymmetricX509Certificate()
                   .WithPublicKey(File.ReadAllBytes(certificate.CerPath))
                   .WithDuration(TimeSpan.FromDays(7))
                   // export the credentials to the file
                   .WithAuthFileToExport(new StreamWriter(new FileStream(authFilePath, FileMode.OpenOrCreate)))
                   .WithPrivateKeyFile(certificate.PfxPath)
                   .WithPrivateKeyPassword(certPassword)
                   .Attach()
                   .WithNewRoleInSubscription(role, subscriptionId)
                   .Create());
        }
コード例 #2
0
        /**
         * Azure Service Principal sample for managing Service Principal -
         *  - Create an Active Directory application
         *  - Create a Service Principal for the application and assign a role
         *  - Export the Service Principal to an authentication file
         *  - Use the file to list subcription virtual machines
         *  - Update the application
         *  - Update the service principal to revoke the password credential and the role
         *  - Delete the Service Principal.
         */
        public static void RunSample(Azure.IAuthenticated authenticated)
        {
            string subscriptionId = authenticated.Subscriptions.List().First <ISubscription>().SubscriptionId;

            Utilities.Log("Selected subscription: " + subscriptionId);
            IActiveDirectoryApplication activeDirectoryApplication = null;
            string authFilePath = Path.Combine(Utilities.ProjectPath, "Asset", "mySamplAuthdFile.azureauth").ToString();

            try
            {
                activeDirectoryApplication = CreateActiveDirectoryApplication(authenticated);
                IServicePrincipal servicePrincipal = CreateServicePrincipalWithRoleForApplicationAndExportToFile(authenticated, activeDirectoryApplication, BuiltInRole.Contributor, subscriptionId, authFilePath);
                // Wait until Service Principal is ready
                SdkContext.DelayProvider.Delay(15);
                UseAuthFile(authFilePath);
                UpdateApplication(authenticated, activeDirectoryApplication);
                UpdateServicePrincipal(authenticated, servicePrincipal);
            }
            finally
            {
                Utilities.Log("Deleting Active Directory application and Service Principal...");
                if (activeDirectoryApplication != null)
                {
                    // this will delete Service Principal as well
                    authenticated.ActiveDirectoryApplications.DeleteById(activeDirectoryApplication.Id);
                }
            }
        }
コード例 #3
0
        private static IActiveDirectoryApplication CreateActiveDirectoryApplication(Azure.IAuthenticated authenticated)
        {
            Utilities.Log("Creating Active Directory application...");
            var name = SdkContext.RandomResourceName("adapp-sample", 20);
            //create a self-sighed certificate
            var         domainName   = name + ".com";
            var         certPassword = "******";
            Certificate certificate  = Certificate.CreateSelfSigned(domainName, certPassword);

            // create Active Directory application
            var activeDirectoryApplication = authenticated.ActiveDirectoryApplications
                                             .Define(name)
                                             .WithSignOnUrl("https://github.com/Azure/azure-sdk-for-java/" + name)
                                             // password credentials definition
                                             .DefinePasswordCredential("password")
                                             .WithPasswordValue("P@ssw0rd")
                                             .WithDuration(TimeSpan.FromDays(700))
                                             .Attach()
                                             // certificate credentials definition
                                             .DefineCertificateCredential("cert")
                                             .WithAsymmetricX509Certificate()
                                             .WithPublicKey(File.ReadAllBytes(certificate.CerPath))
                                             .WithDuration(TimeSpan.FromDays(100))
                                             .Attach()
                                             .Create();

            Utilities.Log(activeDirectoryApplication.Id + " - " + activeDirectoryApplication.ApplicationId);
            return(activeDirectoryApplication);
        }
コード例 #4
0
 public AzureResourceManager(
     AzureCredentials azureCredentials
     )
 {
     _authenticated = Azure
                      .Configure()
                      .Authenticate(azureCredentials);
 }
コード例 #5
0
 private static void UpdateServicePrincipal(Azure.IAuthenticated authenticated, IServicePrincipal servicePrincipal)
 {
     Utilities.Log("Updating Service Principal...");
     servicePrincipal.Update()
     // add another password credentials
     .WithoutCredential("ServicePrincipalAzureSample")
     .WithoutRole(servicePrincipal.RoleAssignments.First())
     .Apply();
 }
コード例 #6
0
        public AzureUtils(string applicationId, string applicationKey, string tenantId, ILogger logger)
        {
            _logger = logger;

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(applicationId,
                                                                                      applicationKey, tenantId, AzureEnvironment.AzureGlobalCloud);

            _authenticatedAzure = Azure.Configure()
                                  .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                                  .Authenticate(credentials);
        }
コード例 #7
0
    private static async Task SyncUsersAsync(Azure.IAuthenticated authenticated,
                                             MyUser[] myUsers, string password)
    {
        Log(0, "===========================================");
        Log(0, "SyncUsersAsync");
        var aadUsers = await LoadActiveDirectoryUsersAsync(authenticated);

        Log(1, $"AAD Users: {aadUsers.Length}");
        Log(1, $"My Users: {myUsers.Length}");
        Log(0, "===========================================");
        await Task.WhenAll(myUsers.Select(x => ProcessUserAsync(x, aadUsers, authenticated, password)));
    }
コード例 #8
0
    private static async Task SyncGroupsAsync(Azure.IAuthenticated authenticated,
                                              MyGroup[] myGroups)
    {
        Log(0, "===========================================");
        Log(0, "SyncGroupsAsync");
        var aadGroups = await LoadActiveDirectoryGroupsAsync(authenticated);

        Log(1, $"AAD Groups: {aadGroups.Length}");
        Log(1, $"My Groups: {myGroups.Length}");
        Log(0, "===========================================");
        await Task.WhenAll(myGroups.Select(x => ProcessGroupAsync(x, aadGroups, authenticated)));
    }
コード例 #9
0
 private static void UpdateApplication(Azure.IAuthenticated authenticated, IActiveDirectoryApplication activeDirectoryApplication)
 {
     Utilities.Log("Updating Active Directory application...");
     activeDirectoryApplication.Update()
     // add another password credentials
     .DefinePasswordCredential("password-1")
     .WithPasswordValue("P@ssw0rd-1")
     .WithDuration(TimeSpan.FromDays(700))
     .Attach()
     // add a reply url
     .WithReplyUrl("http://localhost:8080")
     .Apply();
 }
コード例 #10
0
    private static async Task <IActiveDirectoryGroup?> ProcessGroupAsync(MyGroup item, IActiveDirectoryGroup[] list,
                                                                         Azure.IAuthenticated authenticated)
    {
        Log(0, "===========================================");
        Log(0, "Processing Group");
        Log(1, item);

        var cur = list.FirstOrDefault(x => x.Inner.MailNickname == item.MailNickname);

        if (cur == null && !item.Delete)
        {
            Log(2, "Creating Group");

            cur = await authenticated.ActiveDirectoryGroups
                  .Define(item.Name)
                  .WithEmailAlias(item.MailNickname)
                  .CreateAsync();
        }

        if (cur != null)
        {
            Log(2, cur);
            if (item.Delete)
            {
                Log(2, "Deleting Group");

                await authenticated.ActiveDirectoryGroups.DeleteByIdAsync(cur.Id);

                return(null);
            }

            // // update
            // if (!string.Equals(cur.Name, item.Name, StringComparison.OrdinalIgnoreCase))
            // {
            //     Log(2, "Recreating Group");
            //     await authenticated.ActiveDirectoryGroups.DeleteByIdAsync(cur.Id);
            //
            //
            //     cur = await authenticated.ActiveDirectoryGroups
            //         .Define(item.Name)
            //         .WithEmailAlias(item.MailNickname)
            //         .CreateAsync();
            // }

            // cur.Manager.Inner.Groups.GetWithHttpMessagesAsync()
        }

        return(cur);
    }
        /**
         * Azure Users, Groups and Roles sample.
         * - Create a user
         * - Assign role to AD user
         * - Revoke role from AD user
         * - Get role by scope and role name
         * - Create service principal
         * - Assign role to service principal
         * - Create 2 Active Directory groups
         * - Add the user, the service principal, and the 1st group as members of the 2nd group
         */
        public static void RunSample(Azure.IAuthenticated authenticated)
        {
            string userEmail   = Utilities.CreateRandomName("test");
            string userName    = userEmail.Replace("test", "Test ");
            string spName      = Utilities.CreateRandomName("sp");
            string raName1     = SdkContext.RandomGuid();
            string raName2     = SdkContext.RandomGuid();
            string groupEmail1 = Utilities.CreateRandomName("group1");
            string groupEmail2 = Utilities.CreateRandomName("group2");
            string groupName1  = groupEmail1.Replace("group1", "Group ");
            string groupName2  = groupEmail2.Replace("group2", "Group ");
            String spId        = "";

            string subscriptionId = authenticated.Subscriptions.List().First().SubscriptionId;

            Utilities.Log("Selected subscription: " + subscriptionId);

            // ============================================================
            // Create a user

            Utilities.Log("Creating an Active Directory user " + userName + "...");

            var user = authenticated.ActiveDirectoryUsers
                       .Define(userName)
                       .WithEmailAlias(userEmail)
                       .WithPassword("StrongPass!12")
                       .Create();

            Utilities.Log("Created Active Directory user " + userName);
            Utilities.Print(user);

            // ============================================================
            // Assign role to AD user

            IRoleAssignment roleAssignment1 = authenticated.RoleAssignments
                                              .Define(raName1)
                                              .ForUser(user)
                                              .WithBuiltInRole(BuiltInRole.DnsZoneContributor)
                                              .WithSubscriptionScope(subscriptionId)
                                              .Create();

            Utilities.Log("Created Role Assignment:");
            Utilities.Print(roleAssignment1);

            // ============================================================
            // Revoke role from AD user

            authenticated.RoleAssignments.DeleteById(roleAssignment1.Id);
            Utilities.Log("Revoked Role Assignment: " + roleAssignment1.Id);

            // ============================================================
            // Get role by scope and role name

            IRoleDefinition roleDefinition = authenticated.RoleDefinitions
                                             .GetByScopeAndRoleName("subscriptions/" + subscriptionId, "Contributor");

            Utilities.Print(roleDefinition);

            // ============================================================
            // Create Service Principal

            IServicePrincipal sp = authenticated.ServicePrincipals.Define(spName)
                                   .WithNewApplication("http://" + spName)
                                   .Create();

            // wait till service principal created and propagated
            SdkContext.DelayProvider.Delay(15000);
            Utilities.Log("Created Service Principal:");
            Utilities.Print(sp);
            spId = sp.Id;

            // ============================================================
            // Assign role to Service Principal

            string defaultSubscription = authenticated.Subscriptions.List().First().SubscriptionId;

            IRoleAssignment roleAssignment2 = authenticated.RoleAssignments
                                              .Define(raName2)
                                              .ForServicePrincipal(sp)
                                              .WithBuiltInRole(BuiltInRole.Contributor)
                                              .WithSubscriptionScope(defaultSubscription)
                                              .Create();

            Utilities.Log("Created Role Assignment:");
            Utilities.Print(roleAssignment2);

            // ============================================================
            // Create Active Directory groups

            Utilities.Log("Creating Active Directory group " + groupName1 + "...");
            var group1 = authenticated.ActiveDirectoryGroups
                         .Define(groupName1)
                         .WithEmailAlias(groupEmail1)
                         .Create();

            Utilities.Log("Created Active Directory group " + groupName1);
            Utilities.Print(group1);

            var group2 = authenticated.ActiveDirectoryGroups
                         .Define(groupName2)
                         .WithEmailAlias(groupEmail2)
                         .Create();

            Utilities.Log("Created Active Directory group " + groupName2);
            Utilities.Print(group2);

            Utilities.Log("Adding group members to group " + groupName2 + "...");
            group2.Update()
            .WithMember(user)
            .WithMember(sp)
            .WithMember(group1)
            .Apply();

            Utilities.Log("Group members added to group " + groupName2);
            Utilities.Print(group2);
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: MSSedusch/ResourceTagger
        private static async Task Run()
        {
            string subscriptionIds = ConfigurationManager.AppSettings["subscriptionIds"];
            string ownerTagName    = ConfigurationManager.AppSettings["ownerTagName"];
            string startDate       = DateTime.Now.ToUniversalTime().AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
            string endDate         = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");


            string clientId     = ConfigurationManager.AppSettings["clientId"];
            string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
            string tenantId     = ConfigurationManager.AppSettings["tenantId"];

            AzureCredentialsFactory factory    = new AzureCredentialsFactory();
            AzureCredentials        azureCreds = factory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                              AzureEnvironment.AzureGlobalCloud);

            Azure.IAuthenticated azure = Azure.Configure().Authenticate(azureCreds);

            string body     = @"
{
    ""type"": ""Usage"",
    ""timeframe"": ""Custom"",
    ""timePeriod"": {
        ""from"": """ + startDate + @""",
        ""to"": """ + endDate + @""",
    },
    ""dataset"": {
        ""granularity"": ""Daily"",
        ""aggregation"": {
            ""totalCost"": {
                ""name"": ""PreTaxCost"",
                ""function"": ""Sum""
            }
        },
        ""grouping"": [
            {
            ""type"": ""Dimension"",
            ""name"": ""ResourceGroup""
            }
        ]
    }
}
";
            string currency = String.Empty;
            Dictionary <string, Double> costPerUser  = new Dictionary <string, Double>();
            Dictionary <string, Double> costPerGroup = new Dictionary <string, Double>();
            Dictionary <string, string> groupOwner   = new Dictionary <string, string>();
            string token = await GetOAuthTokenFromAAD();

            foreach (var subscriptionId in subscriptionIds.Split(",", StringSplitOptions.RemoveEmptyEntries))
            {
                var azureSub       = azure.WithSubscription(subscriptionId);
                var resourceGroups = azureSub.ResourceGroups.List();

                string uri = $"https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.CostManagement/query?api-version=2019-01-01";

                while (!String.IsNullOrEmpty(uri))
                {
                    QueryResult result        = null;
                    int         costIndex     = -1;
                    int         currencyIndex = -1;
                    int         groupIndex    = -1;

                    var request = HttpWebRequest.CreateHttp(uri);
                    request.ContentType = "application/json";
                    request.Method      = "POST";
                    request.Headers.Add("Authorization", $"Bearer {token}");
                    try
                    {
                        using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                        {
                            writer.Write(body);
                            writer.Flush();
                        }

                        var response = await request.GetResponseAsync();

                        var responseString = String.Empty;
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            responseString = reader.ReadToEnd();
                        }
                        result        = JsonConvert.DeserializeObject <QueryResult>(responseString);
                        uri           = result.properties.nextLink;
                        costIndex     = GetColumnIndex(result.properties.columns, "PreTaxCost");
                        currencyIndex = GetColumnIndex(result.properties.columns, "Currency");
                        groupIndex    = GetColumnIndex(result.properties.columns, "ResourceGroup");
                        if (costIndex < 0)
                        {
                            Console.WriteLine($"Could not find cost index for subscription {subscriptionId}");
                            continue;
                        }
                    }
                    catch (WebException wex)
                    {
                        string errorMessage = string.Empty;
                        if (wex.Response != null)
                        {
                            using (StreamReader reader = new StreamReader(wex.Response.GetResponseStream()))
                            {
                                errorMessage = reader.ReadToEnd();
                            }
                        }
                        Console.WriteLine($"Error while calculating costs for subscription {subscriptionId}: {wex} ({errorMessage})");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error while calculating costs for subscription {subscriptionId}: {ex}");
                    }

                    if (result != null)
                    {
                        foreach (var group in resourceGroups)
                        {
                            var resourceGroupOwner  = OWNER_UNKNOWN;
                            var defaultKeyValuePair = default(KeyValuePair <String, String>);
                            var ownerTag            = defaultKeyValuePair;
                            if (group.Tags != null)
                            {
                                ownerTag = group.Tags.Where(tag => tag.Key.Equals(ownerTagName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                            }

                            if (!ownerTag.Equals(defaultKeyValuePair))
                            {
                                resourceGroupOwner = ownerTag.Value;
                            }

                            //Console.WriteLine($"Calculating costs for resource group {group.Name} in subscription {subscriptionId} which belongs to {resourceGroupOwner}");

                            string keyNameGroup = $"{subscriptionId}/{group.Name}";
                            if (!costPerUser.ContainsKey(resourceGroupOwner))
                            {
                                costPerUser.Add(resourceGroupOwner, 0);
                            }
                            if (!costPerGroup.ContainsKey(keyNameGroup))
                            {
                                costPerGroup.Add(keyNameGroup, 0);
                            }
                            if (!groupOwner.ContainsKey(keyNameGroup))
                            {
                                groupOwner.Add(keyNameGroup, resourceGroupOwner);
                            }

                            var groupRows = result.properties.rows.Where(rTemp => rTemp[groupIndex].ToString().Equals(group.Name,
                                                                                                                      StringComparison.InvariantCultureIgnoreCase)).ToArray();
                            foreach (var row in groupRows)
                            {
                                costPerUser[resourceGroupOwner] += (Double)row[costIndex];
                                costPerGroup[keyNameGroup]      += (Double)row[costIndex];

                                var currencyOfRow = (string)row[currencyIndex];
                                if (String.IsNullOrEmpty(currency))
                                {
                                    currency = currencyOfRow;
                                }
                                else if (!currency.Equals(currencyOfRow))
                                {
                                    throw new Exception("There are different currencies");
                                }
                            }
                        }
                    }
                }

                Console.WriteLine($"##########################################");
                Console.WriteLine($"Cost between {startDate} and {endDate} per resource group for unknown owner");
                Console.WriteLine($"##########################################");
                var subscriptionRgUnknown = costPerGroup.Where(temp => temp.Key.Split("/")[0].
                                                               Equals(subscriptionId, StringComparison.InvariantCultureIgnoreCase));
                foreach (KeyValuePair <string, double> costEntry in subscriptionRgUnknown.OrderByDescending(temp => temp.Value))
                {
                    if (groupOwner[costEntry.Key].Equals(OWNER_UNKNOWN, StringComparison.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine($"{costEntry.Key}: {currency} {costEntry.Value}");
                    }
                }
            }

            Console.WriteLine($"##########################################");
            Console.WriteLine($"Cost between {startDate} and {endDate} per user");
            Console.WriteLine($"##########################################");
            foreach (KeyValuePair <string, double> costEntry in costPerUser.OrderByDescending(temp => temp.Value))
            {
                Console.WriteLine($"{costEntry.Key}: {currency} {costEntry.Value}");
            }
            Console.WriteLine($"##########################################");
            Console.WriteLine($"Cost between {startDate} and {endDate} per resource group");
            Console.WriteLine($"##########################################");
            foreach (KeyValuePair <string, double> costEntry in costPerGroup.OrderByDescending(temp => temp.Value))
            {
                Console.WriteLine($"{costEntry.Key}: {currency} {costEntry.Value} (owner: {groupOwner[costEntry.Key]})");
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: MSSedusch/ResourceTagger
        public static async Task Run()
        {
            string tag_owner           = GetConfigItem("tag_owner");
            string tag_deallocate      = GetConfigItem("tag_deallocate");
            int    tag_deallocate_days = int.Parse(GetConfigItem("tag_deallocate_days"));
            string tag_deletevm        = GetConfigItem("tag_deletevm");
            int    tag_deletevm_days   = int.Parse(GetConfigItem("tag_deletevm_days"));
            string tag_deleterg        = GetConfigItem("tag_deleterg");
            int    tag_deleterg_days   = int.Parse(GetConfigItem("tag_deleterg_days"));
            string subscriptionIds     = GetConfigItem("subscriptionIds");
            string clientId            = GetConfigItem("clientId");
            string clientSecret        = GetConfigItem("clientSecret");
            string tenantId            = GetConfigItem("tenantId");

            AzureCredentialsFactory factory    = new AzureCredentialsFactory();
            AzureCredentials        azureCreds = factory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                              AzureEnvironment.AzureGlobalCloud);

            Azure.IAuthenticated azure = Azure.Configure().Authenticate(azureCreds);

            foreach (var subscriptionId in subscriptionIds.Split(",", StringSplitOptions.RemoveEmptyEntries))
            {
                Console.WriteLine($"Looking for new resources without an owner tag in subscription {subscriptionId}");

                var azureSub       = azure.WithSubscription(subscriptionId);
                var insightsClient = new InsightsClient(azureCreds);
                insightsClient.SubscriptionId = subscriptionId;

                var resourceGroups = azureSub.ResourceGroups.List();
                foreach (var group in resourceGroups)
                {
                    try
                    {
                        var defaultKeyValuePair = default(KeyValuePair <String, String>);
                        var ownerTag            = defaultKeyValuePair;
                        if (group.Tags != null)
                        {
                            ownerTag = group.Tags.Where(tag => tag.Key.Equals(tag_owner, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        }

                        String endTime    = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                        String resourceId = group.Id;
                        if (ownerTag.Equals(defaultKeyValuePair))
                        {
                            //Console.WriteLine($"Resource group {group.Name} does not contain owner tag...looking in activity log");
                            String startTime = DateTime.Now.ToUniversalTime().AddHours(-25).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

                            string newOwner = UNKNOWN_OWNER;
                            var    resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);

                            if (resourceGroupCreateLogs.Length == 0)
                            {
                                startTime = DateTime.Now.ToUniversalTime().AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                                resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);
                            }
                            if (resourceGroupCreateLogs.Length != 0)
                            {
                                newOwner = resourceGroupCreateLogs[0].Caller;
                            }
                            if (!UNKNOWN_OWNER.Equals(newOwner))
                            {
                                await group.Update().WithTag(tag_owner, newOwner).ApplyAsync();

                                Console.WriteLine($"Resource group {group.Name} tagged with owner {newOwner}");
                            }
                        }
                        else if (UNKNOWN_OWNER.Equals(ownerTag.Value))
                        {
                            bool needsUpdate = false;
                            var  updateGroup = group.Update();
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deallocate, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deallocate, DateTime.Now.ToUniversalTime().AddDays(tag_deallocate_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deletevm, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deletevm, DateTime.Now.ToUniversalTime().AddDays(tag_deletevm_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deleterg, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deleterg, DateTime.Now.ToUniversalTime().AddDays(tag_deleterg_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }

                            if (needsUpdate)
                            {
                                await updateGroup.ApplyAsync();
                            }
                        }
                        else
                        {
                            //Console.WriteLine($"Resource group {group.Name} is already owned by {ownerTag.Value}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception: " + ex);
                    }
                }
            }

            Console.WriteLine("Done Tagging");
        }
コード例 #14
0
        public async Task <Azure.IAuthenticated> GetAzureConnection()
        {
            if (_azure != null)
            {
                return(_azure);
            }

            AzureCredentials credentials;
            string           localDevelopment = Environment.GetEnvironmentVariable("LocalDevelopment", EnvironmentVariableTarget.Process);

            if (!string.IsNullOrEmpty(localDevelopment) &&
                string.Equals(localDevelopment, "true", StringComparison.InvariantCultureIgnoreCase))
            {
                Log.LogDebug($"Get the local service principal for local login");
                var localDevSp = new Principal
                {
                    UserPrincipalName = "LocalLogin",
                    AppId             = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process),
                    TenantId          = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process)
                };
                string clientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
                Log.LogDebug($"AppId: {localDevSp.AppId}, TenantId: {localDevSp.TenantId}");

                credentials = SdkContext
                              .AzureCredentialsFactory
                              .FromServicePrincipal(localDevSp.AppId, clientSecret, localDevSp.TenantId, AzureEnvironment.AzureGlobalCloud);
            }
            else
            {
                Log.LogDebug($"Get the MSI credentials");

                // Because MSI isn't really nicely supported in this nuget package disable it for now and user workaround
                ////credentials = SdkContext
                ////     .AzureCredentialsFactory
                ////     .FromMSI(new MSILoginInformation(MSIResourceType.AppService), AzureEnvironment.AzureGlobalCloud);

                try
                {
                    // START workaround until MSI in this package is really supported
                    string tenantId = Environment.GetEnvironmentVariable("TenantId", EnvironmentVariableTarget.Process);
                    Log.LogDebug($"TenantId: {tenantId}");

                    AzureServiceTokenProvider astp = new AzureServiceTokenProvider();
                    string graphToken = await astp.GetAccessTokenAsync("https://graph.windows.net/", tenantId);

                    AzureServiceTokenProvider astp2 = new AzureServiceTokenProvider();
                    string rmToken = await astp2.GetAccessTokenAsync("https://management.azure.com/", tenantId);

                    Log.LogDebug("Logging with tokens from Token Provider");

                    AzureCredentials customTokenProvider = new AzureCredentials(
                        new TokenCredentials(rmToken),
                        new TokenCredentials(graphToken),
                        tenantId,
                        AzureEnvironment.AzureGlobalCloud);

                    RestClient client = RestClient
                                        .Configure()
                                        .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                        //.WithRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), new IncrementalRetryStrategy(2, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1))))
                                        .WithCredentials(customTokenProvider)
                                        .Build();

                    return(Azure.Authenticate(client, tenantId));
                    // END workaround until MSI in this package is really supported
                }
                catch (Exception ex)
                {
                    Log.LogError(ex, ex.Message);
                    if (ex.InnerException != null)
                    {
                        Log.LogError(ex.InnerException, ex.InnerException.Message);
                    }
                    throw;
                }
            }

            ServiceClientTracing.AddTracingInterceptor(new MicrosoftExtensionsLoggingTracer(Log));
            ServiceClientTracing.IsEnabled = true;

            _azure = Azure
                     .Configure()
                     .WithDelegatingHandler(new HttpLoggingDelegatingHandler())
                     .WithLogLevel(HttpLoggingDelegatingHandler.Level.None)
                     .Authenticate(credentials);

            return(_azure);
        }
        /**
         * Azure Service Principal sample for managing Service Principal -
         *  - Create an Active Directory application
         *  - Create a Service Principal for the application and assign a role
         *  - Export the Service Principal to an authentication file
         *  - Use the file to list subcription virtual machines
         *  - Update the application
         *  - Delete the application and Service Principal.
         */
        public static void RunSample(Azure.IAuthenticated authenticated, AzureEnvironment environment)
        {
            string spName             = Utilities.CreateRandomName("sp");
            string appName            = SdkContext.RandomResourceName("app", 20);
            string appUrl             = "https://" + appName;
            string passwordName1      = SdkContext.RandomResourceName("password", 20);
            string password1          = "P@ssw0rd";
            string passwordName2      = SdkContext.RandomResourceName("password", 20);
            string password2          = "StrongP@ss!12";
            string certName1          = SdkContext.RandomResourceName("cert", 20);
            string raName             = SdkContext.RandomGuid();
            string servicePrincipalId = "";

            try
            {
                // ============================================================
                // Create application

                Utilities.Log("Creating a service principal " + spName + "...");

                IServicePrincipal servicePrincipal = authenticated.ServicePrincipals
                                                     .Define(appName)
                                                     .WithNewApplication(appUrl)
                                                     .DefinePasswordCredential(passwordName1)
                                                     .WithPasswordValue(password1)
                                                     .Attach()
                                                     .DefinePasswordCredential(passwordName2)
                                                     .WithPasswordValue(password2)
                                                     .Attach()
                                                     .DefineCertificateCredential(certName1)
                                                     .WithAsymmetricX509Certificate()
                                                     .WithPublicKey(File.ReadAllBytes(Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.cer")))
                                                     .WithDuration(TimeSpan.FromDays(1))
                                                     .Attach()
                                                     .Create();

                Utilities.Log("Created service principal " + spName + ".");
                Utilities.Print(servicePrincipal);

                servicePrincipalId = servicePrincipal.Id;

                // ============================================================
                // Create role assignment

                Utilities.Log("Creating a Contributor role assignment " + raName + " for the service principal...");

                SdkContext.DelayProvider.Delay(15000);

                IRoleAssignment roleAssignment = authenticated.RoleAssignments
                                                 .Define(raName)
                                                 .ForServicePrincipal(servicePrincipal)
                                                 .WithBuiltInRole(BuiltInRole.Contributor)
                                                 .WithSubscriptionScope(authenticated.Subscriptions.List().First <ISubscription>().SubscriptionId)
                                                 .Create();

                Utilities.Log("Created role assignment " + raName + ".");
                Utilities.Print(roleAssignment);

                // ============================================================
                // Verify the credentials are valid

                Utilities.Log("Verifying password credential " + passwordName1 + " is valid...");

                AzureCredentials testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + passwordName1 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + passwordName1 + " is valid. Exception: " + e.Message);
                }

                Utilities.Log("Verifying password credential " + passwordName2 + " is valid...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + passwordName2 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + passwordName2 + " is valid. Exception: " + e.Message);
                }

                Utilities.Log("Verifying certificate credential " + certName1 + " is valid...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId,
                    Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.pfx"),
                    "Abc123",
                    authenticated.TenantId,
                    environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + certName1 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + certName1 + " is valid. Exception: " + e.Message);
                }

                // ============================================================
                // Revoke access of the 1st password credential
                Utilities.Log("Revoking access for password credential " + passwordName1 + "...");

                servicePrincipal.Update()
                .WithoutCredential(passwordName1)
                .Apply();

                SdkContext.DelayProvider.Delay(15000);

                Utilities.Log("Credential revoked.");

                // ============================================================
                // Verify the revoked password credential is no longer valid

                Utilities.Log("Verifying password credential " + passwordName1 + " is revoked...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Failed to verify " + passwordName1 + " is revoked.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Verified " + passwordName1 + " is revoked. Exception: " + e.Message);
                }

                // ============================================================
                // Revoke the role assignment

                Utilities.Log("Revoking role assignment " + raName + "...");

                authenticated.RoleAssignments.DeleteById(roleAssignment.Id);

                SdkContext.DelayProvider.Delay(5000);

                // ============================================================
                // Verify the revoked password credential is no longer valid

                Utilities.Log("Verifying password credential " + passwordName2 + " has no access to subscription...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription()
                    .ResourceGroups.List();

                    Utilities.Log("Failed to verify " + passwordName2 + " has no access to subscription.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Verified " + passwordName2 + " has no access to subscription. Exception: " + e.Message);
                }
            }
            catch (Exception f)
            {
                Utilities.Log(f.Message);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting application: " + appName);
                    authenticated.ServicePrincipals.DeleteById(servicePrincipalId);
                    Utilities.Log("Deleted application: " + appName);
                }
                catch (Exception e)
                {
                    Utilities.Log("Did not create applications in Azure. No clean up is necessary. Exception: " + e.Message);
                }
            }
        }
コード例 #16
0
 private static Task <IActiveDirectoryUser[]> LoadActiveDirectoryUsersAsync(Azure.IAuthenticated authenticated)
 {
     return(LoadPagedCollectionAsync(authenticated.ActiveDirectoryUsers.ListAsync()));
 }
コード例 #17
0
    private static async Task <IActiveDirectoryUser?> ProcessUserAsync(MyUser item, IActiveDirectoryUser[] list,
                                                                       // ReSharper disable once UnusedParameter.Local
                                                                       Azure.IAuthenticated authenticated, string password)
    {
        async Task ApplyPassword(IActiveDirectoryUser activeDirectoryUser)
        {
            if (item.UseDefaultPassword)
            {
                Log(3, $"Updating UseDefaultPassword: {activeDirectoryUser.UserPrincipalName}");

                var respo = await authenticated.ActiveDirectoryUsers.Inner.UpdateWithHttpMessagesAsync(
                    activeDirectoryUser.UserPrincipalName,
                    new UserUpdateParameters()
                    //{
                    // PasswordProfile = new PasswordProfile(password)
                    // PasswordProfile = new PasswordProfile(SdkContext.RandomResourceName("Pa5$", 15))
                    // {
                    //     ForceChangePasswordNextLogin = false
                    // }
                    //        }
                    );

                var cont = await respo.Response.Content.ReadAsStringAsync();

                Log(3,
                    $"Updating UseDefaultPassword Responce: {activeDirectoryUser.UserPrincipalName}: {respo.Response.StatusCode} {cont}");
            }
        }

        Log(0, "===========================================");
        Log(0, "Processing User");
        Log(1, item);

        var cur = list.FirstOrDefault(x => x.UserPrincipalName == item.Upn);

        if (cur == null && !item.Delete)
        {
            Log(3, $"Creating User: {item.Upn}");

            // var userCreateParameters = new UserCreateParameters()
            // {
            //     MailNickname = item.Upn,
            //     Surname = item.Surname,
            //     GivenName = item.Givenname,
            //     DisplayName = item.Displayname,
            //     UserPrincipalName = item.Upn,
            //     UserType = UserType.Member,
            //     PasswordProfile = new PasswordProfile(SdkContext.RandomResourceName("Pa5$", 15))
            //     // {
            //     //     Password = SdkContext.RandomResourceName("Pa5$",
            //     //         15), // Guid.NewGuid().ToString(), // password,
            //     //     ForceChangePasswordNextLogin = false
            //     // }
            // };
            // userCreateParameters.Validate();
            // //
            // var inner = await authenticated.ActiveDirectoryUsers.Inner.CreateWithHttpMessagesAsync(
            //     userCreateParameters
            // );
            // //
            // Policy.Handle<Exception>()
            //     .RetryAsync(5,
            //         async (exception, i) =>
            //         {
            //             cur = await authenticated.ActiveDirectoryUsers.GetByIdAsync(inner.Body.ObjectId);
            //
            //             if (cur == null)
            //                 throw new Exception();
            //         });


            cur = await authenticated.ActiveDirectoryUsers
                  .Define(item.Displayname)
                  .WithUserPrincipalName(item.Upn)
                  //  .WithPassword(password)
                  .WithPassword(SdkContext.RandomResourceName("Pa5$", 15))
                  .WithPromptToChangePasswordOnLogin(false)
                  .CreateAsync();

            await ApplyPassword(cur);
        }

        if (cur != null)
        {
            if (item.Delete)
            {
                Log(3, $"Deleting User: {cur.UserPrincipalName}");
                await authenticated.ActiveDirectoryUsers.DeleteByIdAsync(cur.Id);

                return(null);
            }

            Log(3, $"Updating User: {cur.UserPrincipalName}");
            Log(3, cur);

            var parameters = new UserUpdateParameters
            {
                Surname     = item.Surname,
                GivenName   = item.Givenname,
                DisplayName = item.Displayname
            };

            //   if (item.UseDefaultPassword)
            //   {
            //       parameters.AdditionalProperties = new Dictionary<string, object>();
            //
            // //      parameters.AdditionalProperties.Add("UseDefaultPassword", item.UseDefaultPassword.ToString());
            //   }

            await authenticated.ActiveDirectoryUsers.Inner.UpdateWithHttpMessagesAsync(cur.UserPrincipalName,
                                                                                       parameters);

            //

            await ApplyPassword(cur);
        }

        if (cur != null)
        {
            Log(0, $"Finished Processing: {cur.UserPrincipalName}");
        }

        return(cur);
    }
コード例 #18
0
        /**
         * Azure Users, Groups and Roles sample.
         * - List users
         * - Get user by email
         * - Assign role to AD user
         * - Revoke role from AD user
         * - Get role by scope and role name
         * - List roles
         * - List Active Directory groups.
         */
        public static void RunSample(Azure.IAuthenticated authenticated)
        {
            string subscriptionId = authenticated.Subscriptions.List().First().SubscriptionId;

            Utilities.Log("Selected subscription: " + subscriptionId);
            string raName1 = SdkContext.RandomGuid();
            // ============================================================
            // List users

            var users = authenticated.ActiveDirectoryUsers.List();

            Utilities.Log("Active Directory Users:");
            foreach (var user in users)
            {
                Utilities.Print(user);
            }

            // ============================================================
            // Get user by email

            IActiveDirectoryUser adUser = authenticated.ActiveDirectoryUsers.GetByName("*****@*****.**");

            Utilities.Log("Found User with email \"[email protected]\": ");
            Utilities.Print(adUser);

            // ============================================================
            // Assign role to AD user

            IRoleAssignment roleAssignment1 = authenticated.RoleAssignments
                                              .Define(raName1)
                                              .ForUser(adUser)
                                              .WithBuiltInRole(BuiltInRole.DnsZoneContributor)
                                              .WithSubscriptionScope(subscriptionId)
                                              .Create();

            Utilities.Log("Created Role Assignment:");
            Utilities.Print(roleAssignment1);

            // ============================================================
            // Revoke role from AD user

            authenticated.RoleAssignments.DeleteById(roleAssignment1.Id);
            Utilities.Log("Revoked Role Assignment: " + roleAssignment1.Id);

            // ============================================================
            // Get role by scope and role name

            IRoleDefinition roleDefinition = authenticated.RoleDefinitions
                                             .GetByScopeAndRoleName("subscriptions/" + subscriptionId, "Contributor");

            Utilities.Print(roleDefinition);

            // ============================================================
            // List roles

            var roles = authenticated.RoleDefinitions
                        .ListByScope("subscriptions/" + subscriptionId);

            Utilities.Log("Roles: ");
            foreach (var role in roles)
            {
                Utilities.Print(role);
            }

            // ============================================================
            // List Active Directory groups

            var groups = authenticated.ActiveDirectoryGroups.List();

            Utilities.Log("Active Directory Groups:");
            foreach (var group in groups)
            {
                Utilities.Print(group);
            }
        }
コード例 #19
0
    private static async Task SyncGroupMembers(Azure.IAuthenticated authenticated, MyGroup[] myGroups)
    {
        Log(0, "===========================================");
        Log(0, "SyncGroupMembers");

        var aadGroups = await LoadActiveDirectoryGroupsAsync(authenticated);

        var aadUsers = await LoadActiveDirectoryUsersAsync(authenticated);

        foreach (var myGroup in myGroups)
        {
            var group = aadGroups.FirstOrDefault(x => x.Inner.MailNickname == myGroup.MailNickname);
            if (group != null && myGroup.Members != null)
            {
                Log(1, "Processing User Membership");
                Log(2, $"{group.Name}");
                var aadMembers = await LoadPagedCollectionAsync(group.ListMembersAsync());

                Log(3, "Checking Members to Remove");
                foreach (var mem in aadMembers.OfType <IActiveDirectoryUser>())
                {
                    Log(4, $"Name: {mem.Name}");

                    var u = aadUsers.FirstOrDefault(x => x.Id == mem.Id);
                    if (u != null)
                    {
                        Log(5, $"UserPrincipalName: {u.UserPrincipalName}");

                        if (!myGroup.Members.Contains(u.UserPrincipalName))
                        {
                            Log(5, "Removing Member from Group");
                            await group.Update()
                            .WithoutMember(mem.Id)
                            .ApplyAsync();
                        }
                    }
                    else
                    {
                        Log(5, "Removing Member from Group");
                        await group.Update()
                        .WithoutMember(mem.Id)
                        .ApplyAsync();
                    }
                }

                Log(3, "Checking Members to Add");
                foreach (var upn in myGroup.Members)
                {
                    Log(4, $"{upn}");
                    var u = aadUsers.FirstOrDefault(x => x.UserPrincipalName == upn);
                    if (u != null)
                    {
                        if (aadMembers.OfType <IActiveDirectoryUser>().All(x => x.Id != u.Id))
                        {
                            Log(5, "Adding Member to Group");
                            await group.Update()
                            .WithMember(u)
                            .ApplyAsync();
                        }
                    }
                }
            }

            if (group != null && myGroup.Groups != null)
            {
                Log(1, "Processing Groups Membership");
                Log(2, $"{group.Name}");
                var aadMembers = await LoadPagedCollectionAsync(group.ListMembersAsync());

                Log(3, "Checking Groups to Remove");
                foreach (var mem in aadMembers.OfType <IActiveDirectoryGroup>())
                {
                    Log(4, $"Name: {mem.Name}");

                    var u = aadGroups.FirstOrDefault(x => x.Id == mem.Id);
                    if (u != null)
                    {
                        Log(5, $"MailNickname: {u.Inner.MailNickname}");

                        if (!myGroup.Groups.Contains(u.Inner.MailNickname))
                        {
                            Log(5, "Removing Group from Group");
                            await group.Update()
                            .WithoutMember(mem.Id)
                            .ApplyAsync();
                        }
                    }
                    else
                    {
                        Log(5, "Removing Group from Group");
                        await group.Update()
                        .WithoutMember(mem.Id)
                        .ApplyAsync();
                    }
                }

                Log(3, "Checking Groups to Add");
                foreach (var nick in myGroup.Groups)
                {
                    Log(4, $"{nick}");
                    var u = aadGroups.FirstOrDefault(x => x.Inner.MailNickname == nick);
                    if (u != null)
                    {
                        if (aadMembers.OfType <IActiveDirectoryGroup>().All(x => x.Id != u.Id))
                        {
                            Log(5, "Adding Group to Group");
                            await group.Update()
                            .WithMember(u)
                            .ApplyAsync();
                        }
                    }
                }
            }
        }
    }