コード例 #1
0
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (CSMSubscriptionClient csmSubscriptionClient = AzureSession.ClientFactory
                                                                     .CreateCustomClient <CSMSubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    return(csmSubscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (RDFESubscriptionClient rdfeSubscriptionClient = AzureSession.ClientFactory
                                                                       .CreateCustomClient <RDFESubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = rdfeSubscriptionClient.Subscriptions.List();
                    return(subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
コード例 #2
0
        public async Task<IEnumerable<Subscription>> ListSubscriptionsAsync(string accessToken)
        {
            var credentials = new TokenCredentials(accessToken);

            using (SubscriptionClient client = new SubscriptionClient(credentials))
            {
                var subscriptionsResult = await client.Subscriptions.ListAsync().ConfigureAwait(false);
                var subscriptions = subscriptionsResult.Subscriptions.OrderBy(x => x.DisplayName).Select(sub => new Subscription { SubscriptionId = sub.SubscriptionId, DisplayName = sub.DisplayName }).ToList();
                return subscriptions;
            }
        }
コード例 #3
0
        public async Task<Subscription> GetSubscription(string accessToken, string subscriptionId)
        {
            var credentials = new TokenCredentials(accessToken);

            using (SubscriptionClient client = new SubscriptionClient(credentials))
            {
                var subscriptionsResult = await client.Subscriptions.GetAsync(subscriptionId, CancellationToken.None);
                return new Subscription
                {
                    SubscriptionId = subscriptionsResult.Subscription.SubscriptionId,
                    DisplayName = subscriptionsResult.Subscription.DisplayName
                };
            }
        }
コード例 #4
0
        public async Task <IList <SubscriptionObject> > GetSubscriptions()
        {
            if (azureADAuthResult == null)
            {
                throw new Exception(Properties.Resources.AzureADAuthResult);
            }

            // Common subscription object to host subscriptions from RDFE & ARM
            IList <SubscriptionObject> subscriptionList = new List <SubscriptionObject>();

            subscriptionCredentials = new Microsoft.Azure.TokenCloudCredentials(azureADAuthResult.AccessToken);
            subscriptionClient      = new Microsoft.Azure.Subscriptions.SubscriptionClient(subscriptionCredentials, new Uri(Properties.Settings.Default.appIdURI));

            var cancelToken = new CancellationToken();

            var tenants = subscriptionClient.Tenants.ListAsync(cancelToken).Result;

            // Get subscriptions for each tenant
            foreach (var tenant in tenants.TenantIds)
            {
                try
                {
                    AuthenticationResult tenantTokenCreds =
                        AuthenticateHelper.RefreshTokenByAuthority(tenant.TenantId,
                                                                   Properties.Settings.Default.appIdURI);
                    subscriptionCredentials = new Microsoft.Azure.TokenCloudCredentials(tenantTokenCreds.AccessToken);
                    var tenantSubscriptionClient =
                        new Microsoft.Azure.Subscriptions.SubscriptionClient(subscriptionCredentials,
                                                                             new Uri(Properties.Settings.Default.appIdURI));
                    var subscriptionListResults = tenantSubscriptionClient.Subscriptions.ListAsync(cancelToken).Result;

                    foreach (var subscription in subscriptionListResults.Subscriptions)
                    {
                        var subList = new SubscriptionObject();
                        subList.Name           = subscription.DisplayName;
                        subList.SubscriptionId = subscription.SubscriptionId;
                        subList.Authority      = tenant.TenantId;
                        subscriptionList.Add(subList);
                    }
                }
                catch (Exception ex)
                {
                    // ignored
                }
            }

            return(subscriptionList);
        }
コード例 #5
0
        public async Task <IList <SubscriptionObject> > GetSubscriptions()
        {
            if (azureADAuthResult == null)
            {
                throw new Exception(Properties.Resources.AzureADAuthResult);
            }

            // Common subscription object to host subscriptions from RDFE & ARM
            IList <SubscriptionObject> subscriptionList = new List <SubscriptionObject>();

            subscriptionCredentials = new Microsoft.Azure.TokenCloudCredentials(azureADAuthResult.AccessToken);
            subscriptionClient      = new Microsoft.Azure.Subscriptions.SubscriptionClient(subscriptionCredentials);

            var cancelToken = new CancellationToken();

            Microsoft.Azure.Subscriptions.Models.SubscriptionListResult subscriptionResults = await subscriptionClient.Subscriptions.ListAsync(cancelToken);

            // Add any ARM subscriptions to the common subscription object
            foreach (var subscription in subscriptionResults.Subscriptions)
            {
                var subList = new SubscriptionObject();
                subList.Name           = subscription.DisplayName;
                subList.SubscriptionId = subscription.SubscriptionId;
                subList.Authority      = "common";
                subscriptionList.Add(subList);
            }

            // Add any RDFE subscriptions to the common subscription object
            IList <Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionListOperationResponse.Subscription> RDFEsubscriptions = await GetRDFESubscriptions();

            foreach (var subscription in RDFEsubscriptions)
            {
                // Only add subscriptions that are not already in the subscription list
                if (subscriptionList.Where(x => x.SubscriptionId == subscription.SubscriptionId).Count() == 0)
                {
                    var subList = new SubscriptionObject();
                    subList.Name           = subscription.SubscriptionName;
                    subList.SubscriptionId = subscription.SubscriptionId;
                    subList.Authority      = subscription.ActiveDirectoryTenantId;
                    subscriptionList.Add(subList);
                }
            }

            return(subscriptionList);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: Wahesh/azure-batch-samples
        private static async Task MainAsync()
        {
            // Obtain an access token using the "common" AAD resource. This allows the application
            // to query AAD for information that lies outside the application's tenant (such as for
            // querying subscription information in your Azure account).
            AuthenticationContext authContext = new AuthenticationContext(AuthorityUri);
            AuthenticationResult authResult = authContext.AcquireToken(ResourceUri,
                                                                       ClientId,
                                                                       new Uri(RedirectUri),
                                                                       PromptBehavior.Auto);

            // The first credential object is used when querying for subscriptions, and is therefore
            // not associated with a specific subscription.
            TokenCloudCredentials subscriptionCreds = new TokenCloudCredentials(authResult.AccessToken);

            string subscriptionId = String.Empty;
            using (SubscriptionClient subClient = new SubscriptionClient(subscriptionCreds))
            {
                // Ask the user to select a subscription. We'll use the selected subscription's
                // ID when constructing another credential object used in initializing the management
                // clients for the remainder of the sample.
                subscriptionId = await SelectSubscriptionAsync(subClient);
            }

            // These credentials are associated with a subscription, and can therefore be used when
            // creating Resource and Batch management clients for use in manipulating entities within
            // the subscription (e.g. resource groups and Batch accounts).
            TokenCloudCredentials creds = new TokenCloudCredentials(subscriptionId, authResult.AccessToken);

            // With the ResourceManagementClient, we create a resource group in which to create the Batch account.
            using (ResourceManagementClient resourceManagementClient = new ResourceManagementClient(creds))
            {
                // Register with the Batch resource provider; this only needs to be performed once per subscription.
                resourceManagementClient.Providers.Register(BatchNameSpace);
                
                string location = await PromptUserForLocationAsync(resourceManagementClient);
                
                await CreateResourceGroupAsync(resourceManagementClient, location);

                await PerformBatchAccountOperationsAsync(creds, location);

                await DeleteResourceGroupAsync(resourceManagementClient);
            }
        }
コード例 #7
0
        public async Task<IList<SubscriptionObject>> GetSubscriptions()
        {
            if (azureADAuthResult == null)
                throw new Exception(Properties.Resources.AzureADAuthResult);

            // Common subscription object to host subscriptions from RDFE & ARM
            IList<SubscriptionObject> subscriptionList = new List<SubscriptionObject>();

            subscriptionCredentials = new Microsoft.Azure.TokenCloudCredentials(azureADAuthResult.AccessToken);
            subscriptionClient = new Microsoft.Azure.Subscriptions.SubscriptionClient(subscriptionCredentials);

            var cancelToken = new CancellationToken();
            Microsoft.Azure.Subscriptions.Models.SubscriptionListResult subscriptionResults = await subscriptionClient.Subscriptions.ListAsync(cancelToken);

            // Add any ARM subscriptions to the common subscription object
            foreach (var subscription in subscriptionResults.Subscriptions)
            {
                var subList = new SubscriptionObject();
                subList.Name = subscription.DisplayName;
                subList.SubscriptionId = subscription.SubscriptionId;
                subList.Authority = "common";
                subscriptionList.Add(subList);
            }

            // Add any RDFE subscriptions to the common subscription object
            IList<Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionListOperationResponse.Subscription> RDFEsubscriptions = await GetRDFESubscriptions();
            foreach (var subscription in RDFEsubscriptions)
            {
                // Only add subscriptions that are not already in the subscription list
                if (subscriptionList.Where(x => x.SubscriptionId == subscription.SubscriptionId).Count() == 0)
                {
                    var subList = new SubscriptionObject();
                    subList.Name = subscription.SubscriptionName;
                    subList.SubscriptionId = subscription.SubscriptionId;
                    subList.Authority = subscription.ActiveDirectoryTenantId;
                    subscriptionList.Add(subList);
                }
            }

            return subscriptionList;
        }
コード例 #8
0
        /// <summary>
        /// Select the subscription id to use in the rest of the sample. 
        /// </summary>
        /// <param name="client">The <see cref="Microsoft.Azure.Subscriptions.SubscriptionClient"/> to use to get all the subscriptions 
        /// under the user's Azure account.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        /// <remarks>If the user has 1 subscription under their Azure account, it is chosen automatically. If the user has more than
        /// one, they are prompted to make a selection.</remarks>
        private static async Task<string> SelectSubscriptionAsync(SubscriptionClient client)
        {
            SubscriptionListResult subs = await client.Subscriptions.ListAsync();

            if (subs.Subscriptions.Any())
            {
                if (subs.Subscriptions.Count > 1)
                {
                    // More than 1 subscription found under the Azure account, prompt the user for the subscription to use
                    string[] subscriptionNames = subs.Subscriptions.Select(s => s.DisplayName).ToArray();
                    string selectedSubscription = PromptForSelectionFromCollection(subscriptionNames, "Enter the number of the Azure subscription to use: ");
                    Subscription selectedSub = subs.Subscriptions.First(s => s.DisplayName.Equals(selectedSubscription));
                    return selectedSub.SubscriptionId;
                }
                else
                {
                    // Only one subscription found, use that one
                    return subs.Subscriptions.First().SubscriptionId;
                }
            }
            else
            {
                throw new InvalidOperationException("No subscriptions found in account. Please create at least one subscription within your Azure account.");
            }
        }
コード例 #9
0
        private static void HandleListSubscriptions(Options options, AuthenticationResult token)
        {
            if (options.ListSubscriptions)
            {
                using (var subscriptionClient = new SubscriptionClient(new TokenCloudCredentials(token.AccessToken)))
                {
                   
                    var subscriptions = subscriptionClient.Subscriptions.ListAsync().GetAwaiter().GetResult().Subscriptions;

                    foreach (var subscription in subscriptions)
                    {
                        Console.WriteLine(JsonConvert.SerializeObject(subscription, Formatting.Indented));
                    }


                }
            }
        }
コード例 #10
0
        private static void HandleDeploy(Options options, AuthenticationContext authContext, AuthenticationResult token, ResourceManagementClient resourceManagementClient)
        {
            if (!string.IsNullOrWhiteSpace(options.Deploy))
            {
                ResourceGroupExtended rg = GetResourceGroup(options, resourceManagementClient);
                //Fix location to displayname from template
                using (var subscriptionClient = new SubscriptionClient(new TokenCloudCredentials(token.AccessToken)))
                {
                    var a = subscriptionClient.Subscriptions.ListLocations(options.SubscriptionId);
                    rg.Location = a.Locations.Single(l => l.Name == rg.Location).DisplayName;
                }

                var graphtoken = authContext.AcquireToken("https://graph.windows.net/", options.ClientID, new Uri(options.RedirectUri), PromptBehavior.Auto);
                var graph = new ActiveDirectoryClient(new Uri("https://graph.windows.net/" + graphtoken.TenantId), () => Task.FromResult(graphtoken.AccessToken));
                var principal = graph.ServicePrincipals.Where(p => p.AppId == options.ApplicaitonId).ExecuteSingleAsync().GetAwaiter().GetResult();


                DeploymentExtended deploymentInfo = null;
                if (!resourceManagementClient.Deployments.CheckExistence(options.ResourceGroup, options.DeployName).Exists)
                {

                    var deployment = new Deployment
                    {
                        Properties = new DeploymentProperties
                        {
                            Mode = DeploymentMode.Incremental, //Dont Delete other resources
                            Template = File.ReadAllText(options.Deploy),
                            Parameters = new JObject(
                                new JProperty("siteName", CreateValue(options.SiteName)),
                                new JProperty("hostingPlanName", CreateValue(options.HostingPlanName)),
                                new JProperty("storageAccountType", CreateValue(options.StorageAccountType)),
                                new JProperty("siteLocation", CreateValue(rg.Location)),
                                new JProperty("sku", CreateValue(options.WebsitePlan)),
                                new JProperty("tenantId", CreateValue(token.TenantId)),
                                new JProperty("objectId", CreateValue(token.UserInfo.UniqueId)),
                                new JProperty("appOwnerTenantId", CreateValue(principal.AppOwnerTenantId.Value.ToString())),
                                new JProperty("appOwnerObjectId", CreateValue(principal.ObjectId))
                                ).ToString(),

                        }
                    };

                    var result = resourceManagementClient.Deployments.CreateOrUpdate(options.ResourceGroup, options.DeployName, deployment);
                    deploymentInfo = result.Deployment;
                }
                else
                {
                    var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName);
                    deploymentInfo = deploymentStatus.Deployment;

                }

                while (!(deploymentInfo.Properties.ProvisioningState == "Succeeded" || deploymentInfo.Properties.ProvisioningState == "Failed"))
                {
                    var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName);
                    deploymentInfo = deploymentStatus.Deployment;
                    Thread.Sleep(5000);
                }
                Console.WriteLine(deploymentInfo.Properties.Outputs);
                var outputs = JObject.Parse(deploymentInfo.Properties.Outputs);
                var storageAccountName = outputs["storageAccount"]["value"].ToString();
                var keyvaultName = outputs["keyvault"]["value"].ToString();

                using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken)))
                {
                    using (var storageClient = new StorageManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken)))
                    {
                        var keys = storageClient.StorageAccounts.ListKeys(options.ResourceGroup, storageAccountName);

                        var vaultInfo = client.Vaults.Get(options.ResourceGroup, keyvaultName);
                        //CHEATING (using powershell application id to get token on behhalf of user);
                        var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob"));
                        var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken));

                        var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult();
                        if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/storage"))
                        {
                            keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key1}").GetAwaiter().GetResult();
                            keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key2}").GetAwaiter().GetResult();


                            var secret = keyvaultClient.GetSecretVersionsAsync(vaultInfo.Vault.Properties.VaultUri, "storage").GetAwaiter().GetResult();
                        }
                    }



                }


            }
        }
コード例 #11
0
        /// <summary>
        /// Select the subscription id to use in the rest of the sample. 
        /// </summary>
        /// <param name="client">The <see cref="Microsoft.Azure.Subscriptions.SubscriptionClient"/> to use to get all the subscriptions 
        /// under the user's Azure account.</param>
        /// <returns>The subscription id to use in the rest of the sample.</returns>
        /// <remarks>If the user has 1 subscription under their Azure account, it is chosen automatically. If the user has more than
        /// one, they are prompted to make a selection.</remarks>
        private static string SelectSubscription(SubscriptionClient client)
        {
            IList<Subscription> subscriptions = client.Subscriptions.List().Subscriptions;
            Subscription selectedSub = subscriptions.First();

            // If there's more than 1 subscription under the Azure account, prompt the user for the subscription to use.
            if (subscriptions.Count > 1)
            {
                string[] subscriptionNames = subscriptions.Select(s => s.DisplayName).ToArray();
                string selectedSubscription = PromptForSelectionFromCollection(subscriptionNames, 
                    "Enter the number of the Azure subscription you would like to use:");
                selectedSub = subscriptions.First(s => s.DisplayName.Equals(selectedSubscription));
            }

            return selectedSub.SubscriptionId;
        }