SetOrAppendProperty() public method

public SetOrAppendProperty ( System.Property property ) : void
property System.Property
return void
コード例 #1
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];
            }
        }
コード例 #2
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)
            {
                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);
            }
        }
コード例 #3
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))
                    {
                        // If no subscription found for the given token/tenant 
                        // discard tempTenant value unless current token/tenant is the last one.
                        if (tempSubscription != null || i == (tenants.Count() - 1))
                        {
                            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;
        }
コード例 #4
0
        public void RefreshContextsFromCache()
        {
            // Authentication factory is already registered in `OnImport()`
            AzureSession.Instance.TryGetComponent(
                PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey,
                out PowerShellTokenCacheProvider tokenCacheProvider);

            string authority = null;

            if (TryGetEnvironment(AzureSession.Instance.GetProperty(AzureSession.Property.Environment), out IAzureEnvironment sessionEnvironment))
            {
                authority = $"{sessionEnvironment.ActiveDirectoryAuthority}organizations";
            }
            var accounts = tokenCacheProvider.ListAccounts(authority);

            if (!accounts.Any())
            {
                if (!Contexts.Any(c => c.Key != "Default" && c.Value.Account.Type == AzureAccount.AccountType.User))
                {
                    // If there are no accounts in the cache, but we never had any existing contexts, return
                    return;
                }

                WriteWarningMessage($"No accounts found in the shared token cache; removing all user contexts.");
                var removedContext = false;
                foreach (var contextName in Contexts.Keys)
                {
                    var context = Contexts[contextName];
                    if (context.Account.Type != AzureAccount.AccountType.User)
                    {
                        continue;
                    }

                    removedContext |= TryCacheRemoveContext(contextName);
                }

                // If no contexts were removed, return now to avoid writing to file later
                if (!removedContext)
                {
                    return;
                }
            }
            else
            {
                var removedUsers   = new HashSet <string>();
                var updatedContext = false;
                foreach (var contextName in Contexts.Keys)
                {
                    var context = Contexts[contextName];
                    if ((string.Equals(contextName, "Default") && context.Account == null) || context.Account.Type != AzureAccount.AccountType.User)
                    {
                        continue;
                    }

                    if (accounts.Any(a => string.Equals(a.Username, context.Account.Id, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    if (!removedUsers.Contains(context.Account.Id))
                    {
                        removedUsers.Add(context.Account.Id);
                        WriteWarningMessage(string.Format(Resources.UserMissingFromSharedTokenCache, context.Account.Id));
                    }

                    updatedContext |= TryCacheRemoveContext(contextName);
                }

                // Check to see if each account has at least one context
                foreach (var account in accounts)
                {
                    if (Contexts.Values.Where(v => v.Account != null && v.Account.Type == AzureAccount.AccountType.User)
                        .Any(v => string.Equals(v.Account.Id, account.Username, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    WriteWarningMessage(string.Format(Resources.CreatingContextsWarning, account.Username));
                    var environment = sessionEnvironment ?? AzureEnvironment.PublicEnvironments
                                      .Where(env => env.Value.ActiveDirectoryAuthority.Contains(account.Environment))
                                      .Select(env => env.Value)
                                      .FirstOrDefault();
                    var azureAccount = new AzureAccount()
                    {
                        Id   = account.Username,
                        Type = AzureAccount.AccountType.User
                    };

                    List <IAccessToken> tokens = null;
                    try
                    {
                        tokens = tokenCacheProvider.GetTenantTokensForAccount(account, environment, WriteWarningMessage);
                    }
                    catch (Exception e)
                    {
                        //In SSO scenario, if the account from token cache has multiple tenants, e.g. MSA account, MSAL randomly picks up
                        //one tenant to ask for token, MSAL will throw exception if MSA home tenant is chosen. The exception is swallowed here as short term fix.
                        WriteWarningMessage(string.Format(Resources.NoTokenFoundWarning, account.Username));
                        EnqueueDebugMessage(e.ToString());
                        continue;
                    }

                    foreach (var token in tokens)
                    {
                        var azureTenant = new AzureTenant()
                        {
                            Id = token.TenantId
                        };
                        azureAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, token.TenantId);
                        var subscriptions = tokenCacheProvider.GetSubscriptionsFromTenantToken(account, environment, token, WriteWarningMessage);
                        if (!subscriptions.Any())
                        {
                            subscriptions.Add(null);
                        }

                        foreach (var subscription in subscriptions)
                        {
                            var context = new AzureContext(subscription, azureAccount, environment, azureTenant);
                            if (!TryGetContextName(context, out string name))
                            {
                                WriteWarningMessage(string.Format(Resources.NoContextNameForSubscription, subscription.Id));
                                continue;
                            }

                            if (!TrySetContext(name, context))
                            {
                                WriteWarningMessage(string.Format(Resources.UnableToCreateContextForSubscription, subscription.Id));
                            }
                            else
                            {
                                updatedContext = true;
                            }
                        }
                    }
                }

                // If the context list was not updated, return now to avoid writing to file later
                if (!updatedContext)
                {
                    return;
                }
            }

            Save(ProfilePath, false);
        }
コード例 #5
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);

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

                    if (Profile.DefaultSubscription == null)
                    {
                        Profile.DefaultSubscription = subscription;
                    }
                }
            }
            return subscriptions;
        }
コード例 #6
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;
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: ms-iot/security
        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();
            }
        }