Пример #1
0
        private void LoadAccountTenants(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment,
                                                                                    AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <Azure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                                                subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                                                .CreateCustomClient <WindowsAzure.Subscriptions.SubscriptionClient>(
                           new TokenCloudCredentials(commonTenantToken.AccessToken),
                           environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                                                subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
Пример #2
0
        public void Login(
            AzureAccount account,
            AzureEnvironment environment)
        {
            ShowDialog promptBehavior = ShowDialog.Always;

            var tenants = ListAccountTenants(account, environment, promptBehavior).ToArray();

            account.SetProperty(AzureAccount.Property.Tenants, null);
            string accountId = null;

            List <AzureSubscription> azureSubscriptions = new List <AzureSubscription>();
            List <string>            authtokens         = new List <string>();

            for (int i = 0; i < tenants.Count(); i++)
            {
                var tenant = tenants[i].Id.ToString();

                IAccessToken token = AcquireAccessToken(account, environment, tenant, ShowDialog.Auto);

                if (accountId == null)
                {
                    accountId = account.Id;
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                }
                else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                }
                else
                {   // if account ID is different from the first tenant account id we need to ignore current tenant
                    Console.WriteLine(string.Format(
                                          "Account ID '{0}' for tenant '{1}' does not match home Account ID '{2}'",
                                          account.Id,
                                          tenant,
                                          accountId));
                    account.Id = accountId;
                    token      = null;
                }

                int found = TryGetTenantSubscription(token, account, environment, tenant, azureSubscriptions, authtokens);
            }

            for (int i = 0; i < azureSubscriptions.Count; ++i)
            {
                var subscription = azureSubscriptions[i];

                Console.WriteLine("Subscription:");
                Console.WriteLine("  Name    = {0}", subscription.Name);
                Console.WriteLine("  Id      = {0}", subscription.Id);
                Console.WriteLine("  State   = {0}", subscription.State);
                Console.WriteLine("  Account = {0}", subscription.Account);

                ShowIoTHubsInSubscription(subscription.Id.ToString(), authtokens[i]).Wait();
            }
        }
Пример #3
0
        public List <AzureSubscription> ImportPublishSettings(string filePath, string environmentName)
        {
            var subscriptions = ListSubscriptionsFromPublishSettingsFile(filePath, environmentName);

            if (subscriptions.Any())
            {
                foreach (var subscription in subscriptions)
                {
                    AzureAccount account = new AzureAccount
                    {
                        Id   = subscription.Account,
                        Type = AzureAccount.AccountType.Certificate
                    };
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                    AddOrSetAccount(account);
                    subscription.SetOrAppendProperty(AzureSubscription.Property.SupportedModes,
                                                     AzureModule.AzureServiceManagement.ToString());

                    if (!Profile.Subscriptions.ContainsKey(subscription.Id))
                    {
                        AddOrSetSubscription(subscription);
                    }

                    if (Profile.DefaultSubscription == null)
                    {
                        Profile.DefaultSubscription = subscription;
                    }
                }
            }
            return(subscriptions);
        }
Пример #4
0
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            string[] tenants = null;
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    tenants = LoadAccountTenants(account, environment, password, promptBehavior);
                }
                else
                {
                    var storedTenants = account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                    if (account.Type == AzureAccount.AccountType.User && storedTenants.Count() == 1)
                    {
                        TracingAdapter.Information(Resources.AuthenticatingForSingleTenant, account.Id, storedTenants[0]);
                        AzureSession.AuthenticationFactory.Authenticate(account, environment, storedTenants[0], password,
                                                                        promptBehavior);
                    }
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List <AzureSubscription> rdfeSubscriptions = ListServiceManagementSubscriptions(account, environment,
                                                                                                password, ShowDialog.Never, tenants).ToList();

                // Set user ID
                foreach (var subscription in rdfeSubscriptions)
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (rdfeSubscriptions.Any())
                {
                    return(rdfeSubscriptions);
                }
                else
                {
                    return(new AzureSubscription[0]);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }
        }
Пример #5
0
        private IEnumerable <AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            string[] tenants = null;
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    tenants = LoadAccountTenants(account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List <AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList(),
                    ListResourceManagerSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return(mergedSubscriptions);
                }
                else
                {
                    return(new AzureSubscription[0]);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return(new AzureSubscription[0]);
            }
        }
Пример #6
0
        public static List <AzureTenant> MergeTenants(
            AzureAccount account,
            IEnumerable <TenantIdDescription> tenants,
            IAccessToken token)
        {
            List <AzureTenant> result = null;

            if (tenants != null)
            {
                var existingTenants = new List <AzureTenant>();
                account.SetProperty(AzureAccount.Property.Tenants, null);
                foreach (var t in tenants)
                {
                    existingTenants.Add(new AzureTenant {
                        Id = new Guid(t.TenantId), Domain = token.GetDomain()
                    });
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, t.TenantId);
                }

                result = existingTenants;
            }

            return(result);
        }
Пример #7
0
        public AzureRMProfile Login(
            AzureAccount account,
            AzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            SecureString password)
        {
            AzureSubscription newSubscription = null;
            AzureTenant       newTenant       = null;
            ShowDialog        promptBehavior  =
                (password == null &&
                 account.Type != AzureAccount.AccountType.AccessToken &&
                 !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                ? ShowDialog.Always : ShowDialog.Never;

            // (tenant and subscription are present) OR
            // (tenant is present and subscription is not provided)
            if (!string.IsNullOrEmpty(tenantId))
            {
                var token = AcquireAccessToken(account, environment, tenantId, password, promptBehavior);
                if (TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() });
                }
            }
            // (tenant is not provided and subscription is present) OR
            // (tenant is not provided and subscription is not provided)
            else
            {
                var tenants = ListAccountTenants(account, environment, password, promptBehavior).Select(s => s.Id.ToString()).ToArray();
                account.SetProperty(AzureAccount.Property.Tenants, null);
                string accountId = null;

                for (int i = 0; i < tenants.Count(); i++)
                {
                    var tenant = tenants[i];

                    AzureTenant       tempTenant;
                    AzureSubscription tempSubscription;

                    IAccessToken token = null;

                    try
                    {
                        token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto);

                        if (accountId == null)
                        {
                            accountId = account.Id;
                            account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                        }
                        else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                        {
                            account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                        }
                        else
                        {   // if account ID is different from the first tenant account id we need to ignore current tenant
                            WriteWarningMessage(string.Format(
                                                    Microsoft.Azure.Commands.Profile.Properties.Resources.AccountIdMismatch,
                                                    account.Id,
                                                    tenant,
                                                    accountId));
                            account.Id = accountId;
                            token      = null;
                        }
                    }
                    catch
                    {
                        WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenant));
                    }

                    if (token != null &&
                        newTenant == null &&
                        TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant))
                    {
                        newTenant       = tempTenant;
                        newSubscription = tempSubscription;
                    }
                }
            }

            if (newSubscription == null)
            {
                if (subscriptionId != null)
                {
                    throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionIdNotFound, account.Id, subscriptionId));
                }
                else if (subscriptionName != null)
                {
                    throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionNameNotFound, account.Id, subscriptionName));
                }

                _profile.Context = new AzureContext(account, environment, newTenant);
            }
            else
            {
                _profile.Context = new AzureContext(newSubscription, account, environment, newTenant);
                if (!newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase))
                {
                    WriteWarningMessage(string.Format(
                                            Microsoft.Azure.Commands.Profile.Properties.Resources.SelectedSubscriptionNotActive,
                                            newSubscription.State));
                }
            }

            _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize();

            return(_profile);
        }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment  = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment  = subscription.Environment;
            }
            else
            {
                subscription      = new AzureSubscription();
                subscription.Id   = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);

            if (environment == null)
            {
                var profileClient = new ProfileClient(Profile);
                environment = profileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not " +
                                            "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This " +
                             "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id   = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName) || Context != null)
            {
                ProfileClient.GetAccount(subscription.Account);
                if (Profile.Context != null && Profile.Context.Subscription != null &&
                    Profile.Context.Subscription.Id == subscription.Id)
                {
                    GeneralUtilities.ClearCurrentStorageAccount();
                }
                var context = new AzureContext(subscription, ProfileClient.GetAccount(subscription.Account), ProfileClient.GetEnvironmentOrDefault(subscription.Environment));
                if (Context != null)
                {
                    context.SetCurrentStorageAccount(this);
                }
                else
                {
                    var client = AzureSession.ClientFactory.CreateClient <StorageManagementClient>(context,
                                                                                                   AzureEnvironment.Endpoint.ServiceManagement);
                    var account = StorageUtilities.GenerateCloudStorageAccount(client, CurrentStorageAccountName);
                    context.SetCurrentStorageAccount(account.ToString(true));
                }
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
Пример #9
0
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment  = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment  = subscription.Environment;
            }
            else
            {
                subscription      = new AzureSubscription();
                subscription.Id   = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);

            if (environment == null)
            {
                environment = DefaultProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not " +
                                            "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This " +
                             "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id   = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName))
            {
                subscription.Properties[AzureSubscription.Property.StorageAccount] = CurrentStorageAccountName;
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
Пример #10
0
        private void InitializeAzureProfile(AzureSMProfile profile, string parameterSet, AzureProfileSettings settings)
        {
            var savedCache = AzureSession.TokenCache;

            AzureSession.TokenCache = TokenCache.DefaultShared;
            try
            {
                var profileClient = new ProfileClient(profile);
                if (settings.Environment == null)
                {
                    settings.Environment = AzureEnvironment.PublicEnvironments["AzureCloud"];
                }
                switch (parameterSet)
                {
                case CertificateParameterSet:
                    profileClient.InitializeProfile(settings.Environment, new Guid(settings.SubscriptionId),
                                                    settings.Certificate,
                                                    settings.StorageAccount);
                    break;

                case CredentialsParameterSet:
                    var userAccount = new AzureAccount
                    {
                        Id   = settings.Credential.UserName,
                        Type = AzureAccount.AccountType.User
                    };
                    profileClient.InitializeProfile(settings.Environment, new Guid(settings.SubscriptionId),
                                                    userAccount,
                                                    settings.Credential.Password, settings.StorageAccount);
                    break;

                case AccessTokenParameterSet:
                    profileClient.InitializeProfile(settings.Environment, new Guid(settings.SubscriptionId),
                                                    settings.AccessToken,
                                                    settings.AccountId, settings.StorageAccount);
                    break;

                case ServicePrincipalParameterSet:
                    var servicePrincipalAccount = new AzureAccount
                    {
                        Id   = settings.Credential.UserName,
                        Type = AzureAccount.AccountType.ServicePrincipal,
                    };
                    servicePrincipalAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, settings.Tenant);
                    profileClient.InitializeProfile(settings.Environment, new Guid(settings.SubscriptionId),
                                                    servicePrincipalAccount,
                                                    settings.Credential.Password, settings.StorageAccount);
                    break;

                case EmptyParameterSet:
                    if (!profile.Environments.ContainsKey(settings.Environment.Name))
                    {
                        profile.Environments.Add(settings.Environment.Name, settings.Environment);
                    }
                    break;
                }
            }
            finally
            {
                AzureSession.TokenCache = savedCache;
            }
        }