Example #1
0
        public IEnumerable <AzureAccount> ToAzureAccounts()
        {
            if (!string.IsNullOrEmpty(ActiveDirectoryUserId))
            {
                AzureAccount userAccount = new AzureAccount
                {
                    Id   = ActiveDirectoryUserId,
                    Type = AzureAccount.AccountType.User
                };

                userAccount.SetProperty(AzureAccount.Property.Subscriptions, new Guid(this.SubscriptionId).ToString());

                if (!string.IsNullOrEmpty(ActiveDirectoryTenantId))
                {
                    userAccount.SetProperty(AzureAccount.Property.Tenants, ActiveDirectoryTenantId);
                }

                yield return(userAccount);
            }

            if (!string.IsNullOrEmpty(ManagementCertificate))
            {
                AzureAccount certificateAccount = new AzureAccount
                {
                    Id   = ManagementCertificate,
                    Type = AzureAccount.AccountType.Certificate
                };

                certificateAccount.SetProperty(AzureAccount.Property.Subscriptions, new Guid(this.SubscriptionId).ToString());

                yield return(certificateAccount);
            }
        }
Example #2
0
        public void AccountMatchingIgnoresCase()
        {
            var    profile         = new AzureSMProfile();
            string accountName     = "*****@*****.**";
            string accountNameCase = "*****@*****.**";
            var    subscriptionId  = Guid.NewGuid();
            var    tenantId        = Guid.NewGuid();
            var    account         = new AzureAccount
            {
                Id   = accountName,
                Type = AzureAccount.AccountType.User
            };

            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            var subscription = new AzureSubscription
            {
                Id          = subscriptionId,
                Account     = accountNameCase,
                Environment = EnvironmentName.AzureCloud
            };

            subscription.SetProperty(AzureSubscription.Property.Default, "true");
            subscription.SetProperty(AzureSubscription.Property.Tenants, tenantId.ToString());
            profile.Accounts.Add(accountName, account);
            profile.Subscriptions.Add(subscriptionId, subscription);
            Assert.NotNull(profile.Context);
            Assert.NotNull(profile.Context.Account);
            Assert.NotNull(profile.Context.Environment);
            Assert.NotNull(profile.Context.Subscription);
            Assert.Equal(account, profile.Context.Account);
            Assert.Equal(subscription, profile.Context.Subscription);
        }
        public static IAzureContextContainer CreateAzureSMProfile(string storageAccount)
        {
#if !NETSTANDARD
            var profile        = new AzureSMProfile();
            var client         = new ProfileClient(profile);
            var tenantId       = Guid.NewGuid();
            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User
            };
            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            var subscription = new AzureSubscription()
            {
                Id   = subscriptionId.ToString(),
                Name = "Test Subscription 1",
            };

            subscription.SetEnvironment(EnvironmentName.AzureCloud);
            subscription.SetAccount(account.Id);
            subscription.SetTenant(tenantId.ToString());
            subscription.SetStorageAccount(storageAccount);
            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsDefault(subscriptionId, account.Id);
            return(profile);
#else
            return(null);
#endif
        }
        public static AzureSMProfile CreateAzureSMProfile(string storageAccount)
        {
            var profile        = new AzureSMProfile();
            var client         = new ProfileClient(profile);
            var tenantId       = Guid.NewGuid();
            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User
            };

            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            var subscription = new AzureSubscription()
            {
                Id          = subscriptionId,
                Name        = "Test Subscription 1",
                Environment = EnvironmentName.AzureCloud,
                Account     = account.Id,
            };

            subscription.SetProperty(AzureSubscription.Property.Tenants, tenantId.ToString());
            subscription.SetProperty(AzureSubscription.Property.StorageAccount, storageAccount);
            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsDefault(subscriptionId, account.Id);
            return(profile);
        }
        protected override void ProcessRecord()
        {
            if (SubscriptionId != null && SubscriptionName != null)
            {
                throw new PSInvalidOperationException(Resources.BothSubscriptionIdAndNameProvided);
            }

            Guid subscrptionIdGuid;

            if (SubscriptionId != null && !Guid.TryParse(SubscriptionId, out subscrptionIdGuid))
            {
                throw new PSInvalidOperationException(Resources.InvalidSubscriptionId);
            }

            AzureAccount azureAccount = new AzureAccount();

            if (!string.IsNullOrEmpty(AccessToken))
            {
                if (string.IsNullOrWhiteSpace(AccountId))
                {
                    throw new PSInvalidOperationException(Resources.AccountIdRequired);
                }

                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
            }
            else if (ServicePrincipal.IsPresent)
            {
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
            }
            else
            {
                azureAccount.Type = AzureAccount.AccountType.User;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { Tenant });
            }

            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = new AzureRMProfile();
            }

            var profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.Profile);

            WriteObject((PSAzureProfile)profileClient.Login(azureAccount, Environment, Tenant, SubscriptionId,
                                                            SubscriptionName, password));
        }
Example #6
0
        private AzureAccount MergeAccountProperties(AzureAccount account1, AzureAccount account2)
        {
            if (account1 == null || account2 == null)
            {
                throw new ArgumentNullException("account1");
            }
            if (!string.Equals(account1.Id, account2.Id, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Account Ids do not match.");
            }
            if (account1.Type != account2.Type)
            {
                throw new ArgumentException("Account1 types do not match.");
            }
            AzureAccount mergeAccount = new AzureAccount
            {
                Id   = account1.Id,
                Type = account1.Type
            };

            // Merge all properties
            foreach (AzureAccount.Property property in Enum.GetValues(typeof(AzureAccount.Property)))
            {
                string propertyValue = account1.GetProperty(property) ?? account2.GetProperty(property);
                if (propertyValue != null)
                {
                    mergeAccount.Properties[property] = propertyValue;
                }
            }

            // Merge Tenants
            var tenants = account1.GetPropertyAsArray(AzureAccount.Property.Tenants)
                          .Union(account2.GetPropertyAsArray(AzureAccount.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Tenants, tenants.ToArray());

            // Merge Subscriptions
            var subscriptions = account1.GetPropertyAsArray(AzureAccount.Property.Subscriptions)
                                .Union(account2.GetPropertyAsArray(AzureAccount.Property.Subscriptions), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.ToArray());

            return(mergeAccount);
        }
Example #7
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();
            }
        }
Example #8
0
        public void AppServiceManagedIdentityWithServiceManagement()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var tenant      = Guid.NewGuid().ToString();
            var userId      = "MSI@2";
            var environment = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var account     = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            const string resource = @"https://management.azure.com/";
            const string serviceManagementResource = @"https://management.core.windows.net/";
            const string endpoint    = @"http://127.0.0.1:41217/MSI/token/";
            var          expectedUri = $"{endpoint}?resource={resource}&api-version=2017-09-01";

            account.SetProperty(AzureAccount.Property.MSILoginUri, endpoint);
            account.SetProperty(AzureAccount.Property.MSILoginSecret, @"bar");
            const string expectedAccessToken = "foo";
            var          expectedExpiresOn   = DateTimeOffset.Parse("1/23/2019 7:15:42 AM +00:00");
            var          responses           = new Dictionary <string, ManagedServiceAppServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                {
                    expectedUri,
                    new ManagedServiceAppServiceTokenInfo()
                    {
                        AccessToken = expectedAccessToken,
                        ExpiresOn   = expectedExpiresOn,
                        Resource    = resource,
                        TokenType   = "Bearer",
                    }
                }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var msat = new ManagedServiceAppServiceAccessToken(account, environment, GetFunctionsResourceId(serviceManagementResource, environment), tenant);

            Assert.Equal(expectedUri, msat.RequestUris.Peek());
            var accessToken = msat.AccessToken;

            Assert.Equal(expectedAccessToken, accessToken);
            Assert.Equal(expectedExpiresOn, msat.ExpiresOn);
        }
Example #9
0
        public void CanAuthenticateUsingMSIDefault()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2);
            string userId  = "*****@*****.**";
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri);

            builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01";
            var defaultUri = builder.Uri.ToString();

            var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                { defaultUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource
                  } },
                { "http://myfunkyurl:10432/oauth2/token?resource=foo&api-version=2018-02-01", new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = "foo"
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var             authFactory = new AuthenticationFactory();
            IRenewableToken token       = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            Assert.Equal(3600, Math.Round(token.ExpiresOn.DateTime.Subtract(DateTime.UtcNow).TotalSeconds));
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };

            account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token");
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo");

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Example #10
0
        public void CanAuthenticateWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder);
            PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            string tenant     = Guid.NewGuid().ToString();
            string userId     = "*****@*****.**";
            var    armToken   = Guid.NewGuid().ToString();
            var    graphToken = Guid.NewGuid().ToString();
            var    kvToken    = Guid.NewGuid().ToString();
            var    account    = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.AccessToken
            };

            account.SetTenants(tenant);
            account.SetAccessToken(armToken);
            account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken);
            account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken);
            var authFactory   = new AuthenticationFactory();
            var environment   = AzureEnvironment.PublicEnvironments.Values.First();
            var checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null);

            VerifyToken(checkArmToken, armToken, userId, tenant);
            checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.ActiveDirectoryServiceEndpointResourceId);
            VerifyToken(checkArmToken, armToken, userId, tenant);
            var checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.GraphEndpointResourceId);

            VerifyToken(checkGraphToken, graphToken, userId, tenant);
            checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.GraphEndpointResourceId);
            VerifyToken(checkGraphToken, graphToken, userId, tenant);
            var checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.AzureKeyVaultServiceEndpointResourceId);

            VerifyToken(checkKVToken, kvToken, userId, tenant);
            checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyToken(checkKVToken, kvToken, userId, tenant);
        }
        private IAzureAccount MergeAccountProperties(IAzureAccount account1, IAzureAccount account2)
        {
            if (account1 == null || account2 == null)
            {
                throw new ArgumentNullException("account1");
            }
            if (!string.Equals(account1.Id, account2.Id, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Account Ids do not match.");
            }
            if (account1.Type != account2.Type)
            {
                throw new ArgumentException("Account1 types do not match.");
            }
            AzureAccount mergeAccount = new AzureAccount
            {
                Id   = account1.Id,
                Type = account1.Type
            };

            foreach (var property in account1.ExtendedProperties.Keys.Union(account2.ExtendedProperties.Keys))
            {
                mergeAccount.SetProperty(property, account1.IsPropertySet(property) ?
                                         account1.GetProperty(property) : account2.GetProperty(property));
            }


            // Merge Tenants
            var tenants = account1.GetPropertyAsArray(AzureAccount.Property.Tenants)
                          .Union(account2.GetPropertyAsArray(AzureAccount.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Tenants, tenants.ToArray());

            // Merge Subscriptions
            var subscriptions = account1.GetPropertyAsArray(AzureAccount.Property.Subscriptions)
                                .Union(account2.GetPropertyAsArray(AzureAccount.Property.Subscriptions), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.ToArray());

            return(mergeAccount);
        }
Example #12
0
        public void CanGetServiceClientCredentialsWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => authenticatorBuilder);
            PowerShellTokenCacheProvider factory = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            string tenant     = Guid.NewGuid().ToString();
            string userId     = "*****@*****.**";
            var    armToken   = Guid.NewGuid().ToString();
            var    graphToken = Guid.NewGuid().ToString();
            var    kvToken    = Guid.NewGuid().ToString();
            var    account    = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.AccessToken
            };

            account.SetTenants(tenant);
            account.SetAccessToken(armToken);
            account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken);
            account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken);
            var authFactory = new AuthenticationFactory();
            var environment = AzureEnvironment.PublicEnvironments.Values.First();
            var mockContext = new AzureContext()
            {
                Account = account
            };
            var credentials = authFactory.GetServiceClientCredentials(mockContext);

            VerifyAccessTokenInServiceClientCredentials(credentials, armToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.Graph);
            VerifyAccessTokenInServiceClientCredentials(credentials, graphToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyAccessTokenInServiceClientCredentials(credentials, kvToken);
        }
        public override void ExecuteCmdlet()
        {
            AzureAccount azureAccount = new AzureAccount();

            azureAccount.Type = ServicePrincipal.IsPresent
                ? AzureAccount.AccountType.ServicePrincipal
                : AzureAccount.AccountType.User;

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { Tenant });
            }

            var account = ProfileClient.AddAccountAndLoadSubscriptions(azureAccount, ProfileClient.GetEnvironmentOrDefault(Environment), password);

            if (account != null)
            {
                WriteVerbose(string.Format(Resources.AddAccountAdded, azureAccount.Id));
                if (ProfileClient.Profile.DefaultSubscription != null)
                {
                    WriteVerbose(string.Format(Resources.AddAccountShowDefaultSubscription,
                                               ProfileClient.Profile.DefaultSubscription.Name));
                }
                WriteVerbose(Resources.AddAccountViewSubscriptions);
                WriteVerbose(Resources.AddAccountChangeSubscription);

                string subscriptionsList = account.GetProperty(AzureAccount.Property.Subscriptions);
                string tenantsList       = account.GetProperty(AzureAccount.Property.Tenants);

                if (subscriptionsList == null)
                {
                    WriteWarning(string.Format(Resources.NoSubscriptionAddedMessage, azureAccount.Id));
                }

                WriteObject(account.ToPSAzureAccount());
            }
        }
Example #14
0
        /// <summary>
        /// Convert the older representation of accounts into the newer representation
        /// </summary>
        /// <param name="account">The legacy account to convert</param>
        /// <returns>An AzureAccount model with data copied from the legacy account</returns>
        public static IAzureAccount Convert(this LegacyAzureAccount account)
        {
            var result = new AzureAccount();

            result.Id   = account.Id;
            result.Type = ConvertAccountType(account.Type);

            foreach (var property in account.Properties)
            {
                result.SetProperty(property.Key, property.Value);
            }

            if (result.IsPropertySet(AzureAccount.Property.AccessToken))
            {
                result.Credential = result.GetAccessToken();
            }

            return(result);
        }
Example #15
0
        private int TryGetTenantSubscription(IAccessToken accessToken,
                                             AzureAccount account,
                                             AzureEnvironment environment,
                                             string tenantId,
                                             List <AzureSubscription> azureSubscriptions,
                                             List <string> authtokens)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                     new List <Microsoft.Azure.Subscriptions.Models.Subscription>())
                                    .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                           "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray());

                foreach (var subscriptionFromServer in subscriptions)
                {
                    var currentSubscription = new AzureSubscription
                    {
                        Id          = new Guid(subscriptionFromServer.SubscriptionId),
                        Account     = accessToken.UserId,
                        Environment = environment.Name,
                        Name        = subscriptionFromServer.DisplayName,
                        State       = subscriptionFromServer.State,
                        Properties  = new Dictionary <AzureSubscription.Property, string>
                        {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    azureSubscriptions.Add(currentSubscription);
                    authtokens.Add(accessToken.AccessToken);
                }

                return(subscriptions.Count());
            }
        }
Example #16
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);
        }
Example #17
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : envSecret;

                var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : envUri;

                if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) &&
                    !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret))
                {
                    // set flag indicating this is AppService Managed Identity ad hoc mode
                    azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used");
                }

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarning,
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();
                    var result = (PSAzureProfile)(task.ConfigureAwait(false).GetAwaiter().GetResult());
                    WriteObject(result);
                });
            }
        }
        private bool TryGetTenantSubscription(IAccessToken accessToken,
                                              AzureAccount account,
                                              AzureEnvironment environment,
                                              string tenantId,
                                              string subscriptionId,
                                              string subscriptionName,
                                              out AzureSubscription subscription,
                                              out AzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>(
                       new TokenCloudCredentials(accessToken.AccessToken),
                       environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                Subscriptions.Models.Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription;
                    }
                    else
                    {
                        var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                             new List <Microsoft.Azure.Subscriptions.Models.Subscription>())
                                            .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                                   "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                        account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray());

                        if (subscriptions.Any())
                        {
                            if (subscriptionName != null)
                            {
                                subscriptionFromServer = subscriptions.FirstOrDefault(
                                    s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                if (subscriptions.Count() > 1)
                                {
                                    WriteWarningMessage(string.Format(
                                                            "TenantId '{0}' contains more than one active subscription. First one will be selected for further use. " +
                                                            "To select another subscription, use Set-AzureRmContext.",
                                                            tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id          = new Guid(subscriptionFromServer.SubscriptionId),
                        Account     = accessToken.UserId,
                        Environment = environment.Name,
                        Name        = subscriptionFromServer.DisplayName,
                        State       = subscriptionFromServer.State,
                        Properties  = new Dictionary <AzureSubscription.Property, string>
                        {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    tenant        = new AzureTenant();
                    tenant.Id     = new Guid(accessToken.TenantId);
                    tenant.Domain = accessToken.GetDomain();
                    return(true);
                }

                subscription = null;

                if (accessToken != null && accessToken.TenantId != null)
                {
                    tenant    = new AzureTenant();
                    tenant.Id = Guid.Parse(accessToken.TenantId);
                    if (accessToken.UserId != null)
                    {
                        var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                        if (domain.Length == 2)
                        {
                            tenant.Domain = domain[1];
                        }
                    }
                    return(true);
                }

                tenant = null;
                return(false);
            }
        }
Example #19
0
        public override void ExecuteCmdlet()
        {
            if (!string.IsNullOrWhiteSpace(SubscriptionId) &&
                !string.IsNullOrWhiteSpace(SubscriptionName))
            {
                throw new PSInvalidOperationException(Resources.BothSubscriptionIdAndNameProvided);
            }

            Guid subscrptionIdGuid;

            if (!string.IsNullOrWhiteSpace(SubscriptionId) &&
                !Guid.TryParse(SubscriptionId, out subscrptionIdGuid))
            {
                throw new PSInvalidOperationException(
                          string.Format(Resources.InvalidSubscriptionId, SubscriptionId));
            }

            AzureAccount azureAccount = new AzureAccount();

            if (!string.IsNullOrEmpty(AccessToken))
            {
                if (string.IsNullOrWhiteSpace(AccountId))
                {
                    throw new PSInvalidOperationException(Resources.AccountIdRequired);
                }

                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
            }
            else if (ServicePrincipal.IsPresent)
            {
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
            }
            else
            {
                azureAccount.Type = AzureAccount.AccountType.User;
            }

            if (!string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.CertificateThumbprint, CertificateThumbprint);
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrEmpty(TenantId))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId });
            }
#pragma warning disable 0618
            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, Environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    AzureRmProfileProvider.Instance.Profile = new AzureRMProfile();
                }

                var profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.Profile);

                WriteObject((PSAzureProfile)profileClient.Login(azureAccount, Environment, TenantId, SubscriptionId,
                                                                SubscriptionName, password));
            }
#pragma warning restore 0618
        }
Example #20
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);
        }
Example #21
0
        public override void ExecuteCmdlet()
        {
            Guid   subscriptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscriptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
                if (SendCertificateChain)
                {
                    azureAccount.SetProperty("SendCertificateChain", SendCertificateChain.ToString());
                    WriteDebug("SendCertificateChain is set.");
                }
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                //ManagedServiceHostName/ManagedServicePort/ManagedServiceSecret are obsolete, should be removed in next major release
                if (this.IsBound(nameof(ManagedServiceHostName)) || this.IsBound(nameof(ManagedServicePort)) || this.IsBound(nameof(ManagedServiceSecret)))
                {
                    WriteWarning(Resources.ObsoleteManagedServiceParameters);
                }

                var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : envSecret;

                var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : envUri;

                if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) &&
                    !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret))
                {
                    // set flag indicating this is AppService Managed Identity ad hoc mode
                    azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used");
                }

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format(Constants.DefaultMsiAccountIdPrefix + "{0}", ManagedServicePort);
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities))
                {
                    commonUtilities = new CommonUtilities();
                    AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities);
                }
                if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication())
                {
                    WriteWarning(Resources.InteractiveAuthNotSupported);
                    return;
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    profileClient.DebugLog   = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();

                    try
                    {
                        //Must not use task.Result as it wraps inner exception into AggregateException
                        var result = (PSAzureProfile)task.GetAwaiter().GetResult();
                        WriteObject(result);
                    }
                    catch (AuthenticationFailedException ex)
                    {
                        if (IsUnableToOpenWebPageError(ex))
                        {
                            WriteWarning(Resources.InteractiveAuthNotSupported);
                            WriteDebug(ex.ToString());
                        }
                        else
                        {
                            if (IsUsingInteractiveAuthentication())
                            {
                                //Display only if user is using Interactive auth
                                WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
                            }
                            WriteDebug(ex.ToString());
                            throw;
                        }
                    }
                });
            }
        }
Example #22
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                break;

            default:
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

// TODO: Remove IfDef
#if NETSTANDARD
            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }
#endif

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    WriteObject((PSAzureProfile)profileClient.Login(
                                    azureAccount,
                                    _environment,
                                    Tenant,
                                    subscriptionId,
                                    subscriptionName,
                                    password,
                                    SkipValidation,
                                    WriteWarning,
                                    name,
                                    !SkipContextPopulation.IsPresent));
                });
            }
        }
Example #23
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            AzureAccount azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                azureAccount.Id   = MyInvocation.BoundParameters.ContainsKey(nameof(AccountId))? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                var builder = new UriBuilder();
                builder.Scheme = "http";
                builder.Host   = ManagedServiceHostName;
                builder.Port   = ManagedServicePort;
                builder.Path   = "/oauth2/token";
                azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, builder.Uri.ToString());
                break;

            default:
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(TenantId))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId });
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    WriteObject((PSAzureProfile)profileClient.Login(
                                    azureAccount,
                                    _environment,
                                    TenantId,
                                    subscriptionId,
                                    subscriptionName,
                                    password,
                                    SkipValidation,
                                    (s) => WriteWarning(s),
                                    name));
                });
            }
        }
Example #24
0
        public override void ExecuteCmdlet()
        {
            Guid   subscriptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscriptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            if (ClientAssertionParameterSet.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase))
            {
                string suppressWarningOrErrorValue = System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME);
                bool.TryParse(suppressWarningOrErrorValue, out bool suppressWarningOrError);
                if (!suppressWarningOrError)
                {
                    WriteWarning("The feature related to parameter name 'FederatedToken' is under preview.");
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalCertificateFileParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ClientAssertionParameterSet:
                azureAccount.Type = "ClientAssertion";
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                azureAccount.Id   = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}";
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrWhiteSpace(CertificatePath))
            {
                var resolvedPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(CertificatePath).FirstOrDefault()?.Path;
                if (string.IsNullOrEmpty(resolvedPath))
                {
                    var parametersLog = $"- Invalid certificate path :'{CertificatePath}'.";
                    throw new InvalidOperationException(parametersLog);
                }
                azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath);
                if (CertificatePassword != null)
                {
                    azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString());
                }
            }

            if ((ParameterSetName == ServicePrincipalCertificateParameterSet || ParameterSetName == ServicePrincipalCertificateFileParameterSet) &&
                SendCertificateChain)
            {
                azureAccount.SetProperty(AzureAccount.Property.SendCertificateChain, SendCertificateChain.ToString());
                bool supressWarningOrError = false;
                try
                {
                    supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME));
                }
                catch
                {
                    //if value of env variable is invalid, use default value of supressWarningOrError
                }
                if (!supressWarningOrError)
                {
                    WriteWarning(Resources.PreviewFunctionMessage);
                }
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }
            if (azureAccount.Type == "ClientAssertion" && FederatedToken != null)
            {
                password = SecureStringExtensions.ConvertToSecureString(FederatedToken);
                azureAccount.SetProperty("ClientAssertion", FederatedToken);
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ClientAssertionWarning, file, directory));
                }
            }

            var resourceId = PreProcessAuthScope();

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities))
                {
                    commonUtilities = new CommonUtilities();
                    AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities);
                }
                if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication())
                {
                    WriteWarning(Resources.InteractiveAuthNotSupported);
                    return;
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    profileClient.DebugLog   = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation,
                                                             resourceId));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();

                    try
                    {
                        //Must not use task.Result as it wraps inner exception into AggregateException
                        var result = (PSAzureProfile)task.GetAwaiter().GetResult();
                        WriteObject(result);
                    }
                    catch (AuthenticationFailedException ex)
                    {
                        if (IsUnableToOpenWebPageError(ex))
                        {
                            WriteWarning(Resources.InteractiveAuthNotSupported);
                            WriteDebug(ex.ToString());
                        }
                        else
                        {
                            if (IsUsingInteractiveAuthentication())
                            {
                                //Display only if user is using Interactive auth
                                WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
                            }
                            WriteDebug(ex.ToString());
                            throw;
                        }
                    }
                });
            }
        }