public async Task <List <AdminSubscription> > GetAzureStackARMSubscriptions(AzureTenant azureTenant) { //_AzureContext.LogProvider.WriteLog("GetAzureARMSubscriptions", "Start - azureTenant: " + azureTenant.ToString()); String subscriptionsUrl = this.GetARMServiceManagementUrl() + "subscriptions?api-version=2015-01-01"; AuthenticationResult authenticationResult = await this.TokenProvider.GetToken(this.GetARMTokenResourceUrl(), azureTenant.TenantId, Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior.Auto); //_AzureContext.StatusProvider.UpdateStatus("BUSY: Getting Subscriptions..."); AzureRestRequest azureRestRequest = new AzureRestRequest(subscriptionsUrl, authenticationResult, "GET", false); AzureRestResponse azureRestResponse = await this.AzureRetriever.GetAzureRestResponse(azureRestRequest); JObject subscriptionsJson = JObject.Parse(azureRestResponse.Response); var subscriptions = from subscription in subscriptionsJson["value"] select subscription; List <AdminSubscription> tenantSubscriptions = new List <AdminSubscription>(); foreach (JObject azureSubscriptionJson in subscriptions) { AdminSubscription azureSubscription = new AdminSubscription(this, azureSubscriptionJson, azureTenant, this.AzureEnvironment, this.GetARMServiceManagementUrl(), this.GetARMTokenResourceUrl()); await azureSubscription.GetAzureStackUserSubscriptions(); tenantSubscriptions.Add(azureSubscription); } return(tenantSubscriptions); }
private async void cboTenant_SelectedIndexChanged(object sender, EventArgs e) { cmbSubscriptions.Items.Clear(); if (cboTenant.SelectedItem != null) { AzureTenant azureTenant = (AzureTenant)cboTenant.SelectedItem; if (_AzureContext.AzureRetriever != null) { foreach (AzureSubscription azureSubscription in azureTenant.Subscriptions) { cmbSubscriptions.Items.Add(azureSubscription); } cmbSubscriptions.Enabled = true; } if (_AzureContext.AzureSubscription != null) { foreach (AzureSubscription azureSubscription in cmbSubscriptions.Items) { if (_AzureContext.AzureSubscription == azureSubscription) { cmbSubscriptions.SelectedItem = azureSubscription; } } } if (cmbSubscriptions.SelectedItem == null && cmbSubscriptions.Items.Count == 1) { cmbSubscriptions.SelectedIndex = 0; } } }
private async void cboTenant_SelectedIndexChanged(object sender, EventArgs e) { _AzureContext.LogProvider.WriteLog("cboTenant_SelectedIndexChanged", "Start"); cmbSubscriptions.Items.Clear(); ComboBox cmbSender = (ComboBox)sender; if (cmbSender.SelectedItem != null) { AzureTenant selectedTenant = (AzureTenant)cmbSender.SelectedItem; await _AzureContext.SetTenantContext(selectedTenant); foreach (AzureSubscription azureSubscription in selectedTenant.Subscriptions) { cmbSubscriptions.Items.Add(azureSubscription); } if (cmbSubscriptions.Items.Count == 1) { cmbSubscriptions.SelectedIndex = 0; } else if (cboTenant.Items.Count > 1) { _AzureContext.StatusProvider.UpdateStatus("WAIT: Awaiting user selection of Azure Subscription"); } } cmbSubscriptions.Enabled = true; _AzureContext.LogProvider.WriteLog("cboTenant_SelectedIndexChanged", "End"); Application.DoEvents(); }
public static AzureTenant ToAzureTenant(this TenantIdDescription other, IAccessToken accessToken) { var tenant = new AzureTenant() { Id = other.TenantId }; tenant.SetProperty(AzureTenant.Property.Directory, accessToken?.GetDomain()); if (!string.IsNullOrEmpty(other.DisplayName)) { tenant.SetOrAppendProperty(AzureTenant.Property.DisplayName, other.DisplayName); } if (other.TenantCategory != null) { tenant.SetOrAppendProperty(AzureTenant.Property.TenantCategory, other.TenantCategory?.ToSerializedValue()); } if (other.Domains != null && other.Domains.Any()) { tenant.SetOrAppendProperty(AzureTenant.Property.Domains, other.Domains.ToArray()); } if (!string.IsNullOrEmpty(other.CountryCode)) { tenant.SetOrAppendProperty(AzureTenant.Property.CountryCode, other.CountryCode); } return(tenant); }
/// <summary> /// Convert the legacy representation of a tenant to the new one /// </summary> /// <param name="tenant">The legacy tenant to convert</param> /// <returns>A new tenant with data copied from the old tenant</returns> public static IAzureTenant Convert(this LegacyAzureTenant tenant) { var result = new AzureTenant(); result.Id = tenant.Id.ToString(); result.Directory = tenant.Domain; return(result); }
public void ProfileSerializeDeserializeWorks() { var dataStore = new MockDataStore(); AzureSession.DataStore = dataStore; var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile); var currentProfile = new AzureRMProfile(profilePath); var tenantId = Guid.NewGuid().ToString(); var environment = new AzureEnvironment { Name = "testCloud", Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } } }; var account = new AzureAccount { Id = "*****@*****.**", Type = AzureAccount.AccountType.User, Properties = { { AzureAccount.Property.Tenants, tenantId } } }; var sub = new AzureSubscription { Account = account.Id, Environment = environment.Name, Id = new Guid(), Name = "Contoso Test Subscription", Properties = { { AzureSubscription.Property.Tenants, tenantId } } }; var tenant = new AzureTenant { Id = new Guid(tenantId), Domain = "contoso.com" }; currentProfile.Context = new AzureContext(sub, account, environment, tenant); currentProfile.Environments[environment.Name] = environment; currentProfile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }; AzureRMProfile deserializedProfile; // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, currentProfile); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one deserializedProfile = (AzureRMProfile)bf.Deserialize(ms); } Assert.NotNull(deserializedProfile); var jCurrentProfile = currentProfile.ToString(); var jDeserializedProfile = deserializedProfile.ToString(); Assert.Equal(jCurrentProfile, jDeserializedProfile); }
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) ? 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); TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant); } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { foreach (var tenant in ListAccountTenants(account, environment, password, promptBehavior)) { AzureTenant tempTenant; AzureSubscription tempSubscription; var token = AcquireAccessToken(account, environment, tenant.Id.ToString(), password, ShowDialog.Auto); if (newTenant == null && TryGetTenantSubscription(token, account, environment, tenant.Id.ToString(), subscriptionId, subscriptionName, out tempSubscription, out tempTenant) && newTenant == null) { 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, subscriptionId)); } else { throw new PSInvalidOperationException(String.Format(Properties.Resources.NoSubscriptionFound, account.Id)); } } _profile.Context = new AzureContext(newSubscription, account, environment, newTenant); _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize(); return(_profile); }
private List <AzureTenant> ListAccountTenants( IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior, Action <string> promptAction) { IList <AzureTenant> result = new List <AzureTenant>(); var commonTenant = account.GetCommonTenant(); try { var commonTenantToken = AcquireAccessToken( account, environment, commonTenant, password, promptBehavior, promptAction); result = SubscriptionAndTenantClient?.ListAccountTenants(commonTenantToken, environment); } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant)); if (account.IsPropertySet(AzureAccount.Property.Tenants)) { result = account.GetPropertyAsArray(AzureAccount.Property.Tenants) .Select(ti => { var tenant = new AzureTenant(); Guid guid; if (Guid.TryParse(ti, out guid)) { tenant.Id = ti; tenant.Directory = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Directory = ti; } return(tenant); }).ToList(); } if (!result.Any()) { throw; } } return(result.ToList()); }
IAzureTenant GetDefaultTenant() { var tenant = new AzureTenant { Id = Guid.NewGuid().ToString(), Directory = "Contoso.OnMicrosoft.com" }; tenant.SetProperty("Correlation", "None"); return(tenant); }
public static AzureTenant ToAzureTenant(this TenantIdDescription other, IAccessToken accessToken) { var tenant = new AzureTenant() { Id = other.TenantId }; tenant.SetProperty(AzureTenant.Property.Directory, accessToken?.GetDomain()); return(tenant); }
public void CanConvertValidAzureTenants(string domain) { var oldTenant = new AzureTenant() { Directory = domain, Id = Guid.NewGuid().ToString(), }; var tenant = (PSAzureTenant)oldTenant; Assert.Equal(oldTenant.Id.ToString(), tenant.Id); Assert.NotNull(tenant.ToString()); Assert.Equal(oldTenant.Id, tenant.TenantId); }
public void TestDeepCopy() { IAzureSubscription subscription = new AzureSubscription() { Id = "DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD", Name = "my sub", State = "my state", }; const string SubHomeTenant = "my home tenant"; subscription.SetHomeTenant(SubHomeTenant); IAzureAccount account = new AzureAccount() { Id = "*****@*****.**", Type = "User" }; IAzureEnvironment environment = new AzureEnvironment() { Name = "my environment" }; IAzureTenant tenant = new AzureTenant() { Id = "DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD" }; IAzureContext original = new AzureContext(subscription, account, environment, tenant); const string PropertyKey = "customPropertyKey"; const string PropertyValue = "customPropertyValue"; original.SetProperty(PropertyKey, PropertyValue); IAzureContext clone = original.DeepCopy(); // references are not equal Assert.NotSame(original, clone); Assert.NotSame(original.Subscription, clone.Subscription); Assert.NotSame(original.Account, clone.Account); Assert.NotSame(original.Environment, clone.Environment); Assert.NotSame(original.Tenant, clone.Tenant); // values are equal Assert.Equal(original.Subscription.Id, clone.Subscription.Id); Assert.Equal(original.Account.Id, clone.Account.Id); Assert.Equal(original.Environment.Name, clone.Environment.Name); Assert.Equal(original.Tenant.Id, clone.Tenant.Id); // custom property Assert.Equal(SubHomeTenant, clone.Subscription.GetHomeTenant()); Assert.Equal(PropertyValue, clone.GetProperty(PropertyKey)); }
private List <AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior) { List <AzureTenant> result = new List <AzureTenant>(); try { var commonTenantToken = AcquireAccessToken(account, environment, AuthenticationFactory.CommonAdTenant, password, promptBehavior); using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>( new TokenCloudCredentials(commonTenantToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager))) { //TODO: Fix subscription client to not require subscriptionId result = account.MergeTenants(subscriptionClient.Tenants.List().TenantIds, commonTenantToken); } } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, AuthenticationFactory.CommonAdTenant)); if (account.IsPropertySet(AzureAccount.Property.Tenants)) { result = account.GetPropertyAsArray(AzureAccount.Property.Tenants) .Select(ti => { var tenant = new AzureTenant(); Guid guid; if (Guid.TryParse(ti, out guid)) { tenant.Id = guid; tenant.Domain = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Domain = ti; } return(tenant); }).ToList(); } if (!result.Any()) { throw; } } return(result); }
public string AddTemporaryTenant() { AzureTenant tenant = new AzureTenant { Id = Guid.NewGuid(), AdminConsented = false, IssValue = Guid.NewGuid().ToString(), Name = "Temporary Tenant", IsTemporaryTenant = true }; Tenants.Add(tenant); return(tenant.IssValue); }
public static async void TestAzure() { var acc = new AzureAccount() { Type = AzureAccount.AccountType.User }; var env = AzureEnvironment.PublicEnvironments["AzureCloud"]; var tenant = new AzureTenant() { Id = Guid.Empty }; var ctx = new AzureContext(acc, env, tenant); //var c = AzureSession.AuthenticationFactory.Authenticate(acc, env, "common", null, ShowDialog.Auto, TokenCache.DefaultShared); //var scred = AzureSession.AuthenticationFactory.GetServiceClientCredentials(ctx); var cred = AzureSession.AuthenticationFactory.Authenticate(acc, env, AuthenticationFactory.CommonAdTenant, null, ShowDialog.Auto, TokenCache.DefaultShared); var u = new Uri(AzureEnvironmentConstants.AzureResourceManagerEndpoint); var tenantsClient = AzureSession.ClientFactory.CreateCustomClient <SubscriptionClient>( new TokenCloudCredentials(cred.AccessToken), u); var tenants = await tenantsClient.Tenants.ListAsync(); foreach (var t in tenants.TenantIds) { //var subCred = AzureSession.AuthenticationFactory.Authenticate(acc, env, t.TenantId, null, ShowDialog.Auto, TokenCache.DefaultShared); //tenantsClient.Credentials = new TokenCloudCredentials(subCred.AccessToken); var subsrciptions = await tenantsClient.Subscriptions.ListAsync(); } //AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(ctx, AzureEnvironment.Endpoint.ResourceManager); var cl = AzureSession.ClientFactory.CreateClient <AutomationManagementClient>(ctx, AzureEnvironment.Endpoint.ResourceManager); var rbs = cl.Runbooks.ListAsync("bula", "kurac"); }
private AzureTenant CreateTenant(string tenantIdOrDomain) { var tenant = new AzureTenant(); Guid tenantIdGuid; if (Guid.TryParse(tenantIdOrDomain, out tenantIdGuid)) { tenant.Id = tenantIdGuid.ToString(); } else { tenant.Directory = tenantIdOrDomain; } return(tenant); }
private async void rbSameUserDifferentSubscription_CheckedChanged(object sender, EventArgs e) { if (!_IsInitializing) { if (rbSameUserDifferentSubscription.Checked) { _AzureLoginContextViewer.AzureContext.TokenProvider.LastUserInfo = _AzureLoginContextViewer.ExistingContext.TokenProvider.LastUserInfo; _AzureLoginContextViewer.AzureContext.AzureEnvironment = _AzureLoginContextViewer.ExistingContext.AzureEnvironment; _AzureLoginContextViewer.AzureContextSelectedType = AzureContextSelectedType.SameUserDifferentSubscription; _AzureLoginContextViewer.AzureContext.LoginPromptBehavior = PromptBehavior.Auto; if (cboTenant.SelectedIndex == -1 && cboTenant.Items.Count > 0) { cboTenant.SelectedIndex = 0; } if (cboTenant.SelectedItem != null) { AzureTenant azureTenant = (AzureTenant)cboTenant.SelectedItem; if (_AzureLoginContextViewer.AzureContext.AzureTenant != azureTenant) { await _AzureLoginContextViewer.AzureContext.SetTenantContext(azureTenant); } } if (cboSubscription.SelectedIndex == -1 && cboSubscription.Items.Count > 0) { cboSubscription.SelectedIndex = 0; } if (cboSubscription.SelectedItem != null) { AzureSubscription azureSubscription = (AzureSubscription)cboSubscription.SelectedItem; if (_AzureLoginContextViewer.AzureContext.AzureSubscription != azureSubscription) { await _AzureLoginContextViewer.AzureContext.SetSubscriptionContext(azureSubscription); } } } } await azureArmLoginControl1.BindContext(_AzureLoginContextViewer.AzureContext, _AzureEnvironments, _UserDefinedAzureEnvironments); cboTenant.Enabled = rbSameUserDifferentSubscription.Checked; cboSubscription.Enabled = rbSameUserDifferentSubscription.Checked; _AzureLoginContextViewer.UpdateLabels(); }
private static AzureTenant CreateTenantFromString(string tenantOrDomain) { AzureTenant result = new AzureTenant(); Guid id; if (Guid.TryParse(tenantOrDomain, out id)) { result.Id = id; } else { result.Domain = tenantOrDomain; } return(result); }
private static AzureTenant CreateTenantFromString(string tenantOrDomain, string accessTokenTenantId) { AzureTenant result = new AzureTenant(); Guid id; if (Guid.TryParse(tenantOrDomain, out id)) { result.Id = tenantOrDomain; } else { result.Id = accessTokenTenantId; result.Directory = tenantOrDomain; } return(result); }
private void cboTenant_SelectedIndexChanged(object sender, EventArgs e) { cboSubscription.Items.Clear(); if (cboTenant.SelectedItem != null) { AzureTenant azureTenant = (AzureTenant)cboTenant.SelectedItem; foreach (AzureSubscription azureSubscription in azureTenant.Subscriptions) { if (azureSubscription != _AzureLoginContextViewer.ExistingContext.AzureSubscription) // Do not add if same as existing subscription. Combobox intent is to pick a different subscription. { cboSubscription.Items.Add(azureSubscription); } } if (cboSubscription.Items.Count > 0) { cboSubscription.SelectedIndex = 0; } } }
private AssociationStatusEnum ConvertTemporaryTenantToPermanentTenant(string temporaryIssValue, string tenantId) { string issValue = $"https://sts.windows.net/{tenantId}/"; if (Tenants.Any(x => x.IssValue == issValue)) { return(AssociationStatusEnum.AlreadyAssociated); } AzureTenant tenant = Tenants.SingleOrDefault(x => x.IssValue == temporaryIssValue && x.IsTemporaryTenant); if (tenant == null) { return(AssociationStatusEnum.TenantNotFound); } tenant.IssValue = issValue; tenant.AdminConsented = true; tenant.IsTemporaryTenant = false; return(AssociationStatusEnum.Associated); }
protected void grdAzureTenants_RowDeleting(object sender, GridViewDeleteEventArgs e) { if (ValidatePrerequisite() != ConfigStatus.AllGood) { return; } if (PersistedObject.AzureTenants == null) { return; } GridViewRow rowToDelete = grdAzureTenants.Rows[e.RowIndex]; Guid Id = new Guid(rowToDelete.Cells[0].Text); AzureTenant tenantToRemove = PersistedObject.AzureTenants.FirstOrDefault(x => x.Identifier == Id); if (tenantToRemove != null) { PersistedObject.AzureTenants.Remove(tenantToRemove); CommitChanges(); ClaimsProviderLogging.Log($"Azure AD tenant '{tenantToRemove.Name}' was successfully removed from configuration '{PersistedObjectName}'", TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Configuration); PopulateConnectionsGrid(); } }
private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode) { TestEnvironment currentEnvironment = null; if (mode == AzureModule.AzureResourceManager) { currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); } else { currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment(); } if (currentEnvironment.UserName == null) { currentEnvironment.UserName = "******"; } SetAuthenticationFactory(mode, currentEnvironment); AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName }; Debug.Assert(currentEnvironment != null); environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = currentEnvironment.BaseUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.Graph] = currentEnvironment.Endpoints.GraphUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix] = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix] = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName)) { ProfileClient.AddOrSetEnvironment(environment); } if (!AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey(testEnvironmentName)) { AzureRmProfileProvider.Instance.Profile.Environments[testEnvironmentName] = environment; } if (currentEnvironment.SubscriptionId != null) { testSubscription = new AzureSubscription() { Id = new Guid(currentEnvironment.SubscriptionId), Name = testSubscriptionName, Environment = testEnvironmentName, Account = currentEnvironment.UserName, Properties = new Dictionary <AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" }, { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT") }, } }; testAccount = new AzureAccount() { Id = currentEnvironment.UserName, Type = AzureAccount.AccountType.User, Properties = new Dictionary <AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId }, } }; ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription; ProfileClient.Profile.Accounts[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account); var testTenant = new AzureTenant() { Id = Guid.NewGuid() }; if (!string.IsNullOrEmpty(currentEnvironment.Tenant)) { Guid tenant; if (Guid.TryParse(currentEnvironment.Tenant, out tenant)) { testTenant.Id = tenant; } } AzureRmProfileProvider.Instance.Profile.Context = new AzureContext(testSubscription, testAccount, environment, testTenant); } }
public async Task BindContext(AzureContext azureContext, List <AzureEnvironment> azureEnvironments, List <AzureEnvironment> userDefinedAzureEnvironments) { _AzureContext = azureContext; cboAzureEnvironment.Items.Clear(); foreach (AzureEnvironment azureEnvironment in azureEnvironments) { cboAzureEnvironment.Items.Add(azureEnvironment); } foreach (AzureEnvironment azureEnvironment in userDefinedAzureEnvironments) { cboAzureEnvironment.Items.Add(azureEnvironment); } if (_AzureContext.AzureEnvironment != null) { int environmentIndex = cboAzureEnvironment.FindStringExact(_AzureContext.AzureEnvironment.ToString()); if (environmentIndex >= 0) { cboAzureEnvironment.SelectedIndex = environmentIndex; } } if (cboAzureEnvironment.SelectedIndex < 0) { cboAzureEnvironment.SelectedIndex = 0; } if (_AzureContext.TokenProvider == null || _AzureContext.TokenProvider.LastUserInfo == null) { lblAuthenticatedUser.Text = "-"; cboAzureEnvironment.Enabled = true; btnAuthenticate.Text = "Sign In"; } else { lblAuthenticatedUser.Text = _AzureContext.TokenProvider.LastUserInfo.DisplayableId; cboAzureEnvironment.Enabled = false; btnAuthenticate.Text = "Sign Out"; } cboTenant.Items.Clear(); if (_AzureContext.AzureRetriever != null && _AzureContext.TokenProvider != null && _AzureContext.TokenProvider.LastUserInfo != null) { foreach (AzureTenant azureTenant in await _AzureContext.GetAzureARMTenants()) { if (azureTenant.Subscriptions.Count > 0) // Only add Tenants that have one or more Subscriptions { cboTenant.Items.Add(azureTenant); } } cboTenant.Enabled = true; if (_AzureContext.AzureTenant != null) { foreach (AzureTenant azureTenant in cboTenant.Items) { if (_AzureContext.AzureTenant == azureTenant) { cboTenant.SelectedItem = azureTenant; } } } if (cboTenant.SelectedItem != null) { AzureTenant selectedTenant = (AzureTenant)cboTenant.SelectedItem; cmbSubscriptions.Items.Clear(); if (_AzureContext.AzureRetriever != null) { foreach (AzureSubscription azureSubscription in await selectedTenant.GetAzureARMSubscriptions(_AzureContext, false)) { cmbSubscriptions.Items.Add(azureSubscription); } cmbSubscriptions.Enabled = true; } if (_AzureContext.AzureSubscription != null) { foreach (AzureSubscription azureSubscription in cmbSubscriptions.Items) { if (_AzureContext.AzureSubscription == azureSubscription) { cmbSubscriptions.SelectedItem = azureSubscription; } } } } } _AzureContext.StatusProvider.UpdateStatus("Ready"); }
public void SavingProfileWorks() { string expected = @"{ ""EnvironmentTable"": { ""testCloud"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""ServiceManagementUrl"": null, ""ResourceManagerUrl"": null, ""ManagementPortalUrl"": null, ""PublishSettingsFileUrl"": null, ""ActiveDirectoryAuthority"": ""http://contoso.com"", ""GalleryUrl"": null, ""GraphUrl"": null, ""ActiveDirectoryServiceEndpointResourceId"": null, ""StorageEndpointSuffix"": null, ""SqlDatabaseDnsSuffix"": null, ""TrafficManagerDnsSuffix"": null, ""AzureKeyVaultDnsSuffix"": null, ""AzureKeyVaultServiceEndpointResourceId"": null, ""GraphEndpointResourceId"": null, ""DataLakeEndpointResourceId"": null, ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null, ""AzureDataLakeStoreFileSystemEndpointSuffix"": null, ""AdTenant"": null, ""VersionProfiles"": [], ""ExtendedProperties"": {} } }, ""Contexts"": { ""Default"": { ""Account"": { ""Id"": ""*****@*****.**"", ""Credential"": null, ""Type"": ""User"", ""TenantMap"": {}, ""ExtendedProperties"": { ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"" } }, ""Tenant"": { ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"", ""Directory"": ""contoso.com"", ""ExtendedProperties"": {} }, ""Subscription"": { ""Id"": ""00000000-0000-0000-0000-000000000000"", ""Name"": ""Contoso Test Subscription"", ""State"": ""Enabled"", ""ExtendedProperties"": { ""Account"": ""*****@*****.**"", ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"", ""Environment"": ""testCloud"" } }, ""Environment"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""ServiceManagementUrl"": null, ""ResourceManagerUrl"": null, ""ManagementPortalUrl"": null, ""PublishSettingsFileUrl"": null, ""ActiveDirectoryAuthority"": ""http://contoso.com"", ""GalleryUrl"": null, ""GraphUrl"": null, ""ActiveDirectoryServiceEndpointResourceId"": null, ""StorageEndpointSuffix"": null, ""SqlDatabaseDnsSuffix"": null, ""TrafficManagerDnsSuffix"": null, ""AzureKeyVaultDnsSuffix"": null, ""AzureKeyVaultServiceEndpointResourceId"": null, ""GraphEndpointResourceId"": null, ""DataLakeEndpointResourceId"": null, ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null, ""AzureDataLakeStoreFileSystemEndpointSuffix"": null, ""AdTenant"": null, ""VersionProfiles"": [], ""ExtendedProperties"": {} }, ""VersionProfile"": null, ""TokenCache"": { ""CacheData"": ""AgAAAAAAAAA="" }, ""ExtendedProperties"": {} } }, ""ExtendedProperties"": {} }"; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ProfileFile); var dataStore = new MockDataStore(); AzureSession.Instance.DataStore = dataStore; AzureRmProfile profile = new AzureRmProfile(path); var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6"); var environment = new AzureEnvironment { Name = "testCloud", ActiveDirectoryAuthority = "http://contoso.com" }; var account = new AzureAccount { Id = "*****@*****.**", Type = AzureAccount.AccountType.User, }; account.SetTenants(tenantId.ToString()); var sub = new AzureSubscription { Id = new Guid().ToString(), Name = "Contoso Test Subscription", State = "Enabled", }; sub.SetAccount(account.Id); sub.SetEnvironment(environment.Name); sub.SetTenant(tenantId.ToString()); var tenant = new AzureTenant { Id = tenantId.ToString(), Directory = "contoso.com" }; profile.DefaultContext = new AzureContext(sub, account, environment, tenant); profile.EnvironmentTable[environment.Name] = environment; profile.DefaultContext.TokenCache = new AuthenticationStoreTokenCache(new AzureTokenCache { CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 } }); profile.Save(); string actual = dataStore.ReadFileAsText(path); Assert.Equal(expected, actual); }
private List <AzureTenant> ListAccountTenants( IAzureAccount account, IAzureEnvironment environment, SecureString password, string promptBehavior, Action <string> promptAction) { List <AzureTenant> result = new List <AzureTenant>(); var commonTenant = GetCommonTenant(account); try { var commonTenantToken = AcquireAccessToken( account, environment, commonTenant, password, promptBehavior, promptAction); SubscriptionClient subscriptionClient = null; try { subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(commonTenantToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers()); //TODO: Fix subscription client to not require subscriptionId result = account.MergeTenants(subscriptionClient.Tenants.List(), commonTenantToken); } finally { // In test mode, we are reusing the client since disposing of it will // fail some tests (due to HttpClient being null) if (subscriptionClient != null && !TestMockSupport.RunningMocked) { subscriptionClient.Dispose(); } } } catch { WriteWarningMessage(string.Format(ProfileMessages.UnableToAqcuireToken, commonTenant)); if (account.IsPropertySet(AzureAccount.Property.Tenants)) { result = account.GetPropertyAsArray(AzureAccount.Property.Tenants) .Select(ti => { var tenant = new AzureTenant(); Guid guid; if (Guid.TryParse(ti, out guid)) { tenant.Id = ti; tenant.Directory = AccessTokenExtensions.GetDomain(account.Id); } else { tenant.Directory = ti; } return(tenant); }).ToList(); } if (!result.Any()) { throw; } } return(result); }
public AzureRmProfile Login( IAzureAccount account, IAzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, SecureString password, bool skipValidation, Action <string> promptAction, string name = null) { IAzureSubscription newSubscription = null; IAzureTenant newTenant = null; string promptBehavior = (password == null && account.Type != AzureAccount.AccountType.AccessToken && account.Type != AzureAccount.AccountType.ManagedService && !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) ? ShowDialog.Always : ShowDialog.Never; if (skipValidation) { if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(tenantId)) { throw new PSInvalidOperationException(Resources.SubscriptionOrTenantMissing); } newSubscription = new AzureSubscription { Id = subscriptionId }; newSubscription.SetOrAppendProperty(AzureSubscription.Property.Tenants, tenantId); newSubscription.SetOrAppendProperty(AzureSubscription.Property.Account, account.Id); newTenant = new AzureTenant { Id = tenantId }; } else { // (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, promptAction); 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, promptAction) .Select(s => s.Id.ToString()).ToList(); account.SetProperty(AzureAccount.Property.Tenants, null); string accountId = null; foreach (var tenant in tenants) { IAzureTenant tempTenant; IAzureSubscription tempSubscription; IAccessToken token = null; try { token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto, null); 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( ProfileMessages.AccountIdMismatch, account.Id, tenant, accountId)); account.Id = accountId; token = null; } } catch { WriteWarningMessage(string.Format(ProfileMessages.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 || tenant.Equals(tenants[tenants.Count - 1])) { newTenant = tempTenant; newSubscription = tempSubscription; } } } } } if (newSubscription == null) { if (subscriptionId != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionIdNotFound, account.Id, subscriptionId)); } else if (subscriptionName != null) { throw new PSInvalidOperationException(String.Format(ResourceMessages.SubscriptionNameNotFound, account.Id, subscriptionName)); } var newContext = new AzureContext(account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } } else { var newContext = new AzureContext(newSubscription, account, environment, newTenant); if (!_profile.TrySetDefaultContext(name, newContext)) { WriteWarningMessage(string.Format(ProfileMessages.CannotSetDefaultContext, newContext.ToString())); } if (!skipValidation && !newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase)) { WriteWarningMessage(string.Format( ProfileMessages.SelectedSubscriptionNotActive, newSubscription.State)); } } _profile.DefaultContext.TokenCache = _cache; return(_profile.ToProfile()); }
private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode) { TestEnvironment currentEnvironment = null; if (mode == AzureModule.AzureResourceManager) { #if !NETSTANDARD currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); #else currentEnvironment = TestEnvironmentFactory.GetTestEnvironment(); #endif } else { #if !NETSTANDARD currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment(); #else throw new NotSupportedException("RDFE environment is not supported in .Net Core"); #endif } if (currentEnvironment.UserName == null) { currentEnvironment.UserName = "******"; } SetAuthenticationFactory(mode, currentEnvironment); AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName }; Debug.Assert(currentEnvironment != null); environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri; environment.GalleryUrl = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri; environment.ServiceManagementUrl = currentEnvironment.BaseUri.AbsoluteUri; environment.ResourceManagerUrl = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri; environment.GraphUrl = currentEnvironment.Endpoints.GraphUri.AbsoluteUri; environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix environment.AzureDataLakeStoreFileSystemEndpointSuffix = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix #if !NETSTANDARD if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName)) { ProfileClient.AddOrSetEnvironment(environment); } #endif if (!AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable.ContainsKey(testEnvironmentName)) { AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable[testEnvironmentName] = environment; } if (currentEnvironment.SubscriptionId != null) { testSubscription = new AzureSubscription() { Id = currentEnvironment.SubscriptionId, Name = testSubscriptionName, }; testSubscription.SetEnvironment(testEnvironmentName); testSubscription.SetAccount(currentEnvironment.UserName); testSubscription.SetDefault(); testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")); testAccount = new AzureAccount() { Id = currentEnvironment.UserName, Type = AzureAccount.AccountType.User, }; testAccount.SetSubscriptions(currentEnvironment.SubscriptionId); #if !NETSTANDARD ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription; ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount()); #endif var testTenant = new AzureTenant() { Id = Guid.NewGuid().ToString() }; if (!string.IsNullOrEmpty(currentEnvironment.Tenant)) { Guid tenant; if (Guid.TryParse(currentEnvironment.Tenant, out tenant)) { testTenant.Id = currentEnvironment.Tenant; } } AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, environment, testTenant); } }
public void SavingProfileWorks() { string expected = @"{ ""Environments"": { ""testCloud"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""Endpoints"": { ""ActiveDirectory"": ""http://contoso.com"" } } }, ""Context"": { ""Account"": { ""Id"": ""*****@*****.**"", ""Type"": 1, ""Properties"": { ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"" } }, ""Subscription"": { ""Id"": ""00000000-0000-0000-0000-000000000000"", ""Name"": ""Contoso Test Subscription"", ""Environment"": ""testCloud"", ""Account"": ""*****@*****.**"", ""State"": ""Enabled"", ""Properties"": { ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"" } }, ""Environment"": { ""Name"": ""testCloud"", ""OnPremise"": false, ""Endpoints"": { ""ActiveDirectory"": ""http://contoso.com"" } }, ""Tenant"": { ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"", ""Domain"": ""contoso.com"" }, ""TokenCache"": ""AQIDBAUGCAkA"" } }"; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile); var dataStore = new MockDataStore(); AzureSession.DataStore = dataStore; AzureRMProfile profile = new AzureRMProfile(path); var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6"); var environment = new AzureEnvironment { Name = "testCloud", Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } } }; var account = new AzureAccount { Id = "*****@*****.**", Type = AzureAccount.AccountType.User, Properties = { { AzureAccount.Property.Tenants, tenantId.ToString() } } }; var sub = new AzureSubscription { Account = account.Id, Environment = environment.Name, Id = new Guid(), Name = "Contoso Test Subscription", State = "Enabled", Properties = { { AzureSubscription.Property.Tenants, tenantId.ToString() } } }; var tenant = new AzureTenant { Id = tenantId, Domain = "contoso.com" }; profile.Context = new AzureContext(sub, account, environment, tenant); profile.Environments[environment.Name] = environment; profile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }; profile.Save(); string actual = dataStore.ReadFileAsText(path); Assert.Equal(expected, actual); }
private bool TryGetTenantSubscription(IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, out IAzureSubscription subscription, out IAzureTenant tenant) { using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>( environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials, AzureSession.Instance.ClientFactory.GetCustomHandlers())) { Subscription subscriptionFromServer = null; try { if (subscriptionId != null) { subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId); } else { var subscriptions = (subscriptionClient.ListAll().ToList() ?? new List <Subscription>()) .Where(s => "enabled".Equals(s.State.ToString(), StringComparison.OrdinalIgnoreCase) || "warned".Equals(s.State.ToString(), 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 = subscriptionFromServer.SubscriptionId, Name = subscriptionFromServer.DisplayName, State = subscriptionFromServer.State.ToString() }; subscription.SetAccount(accessToken.UserId); subscription.SetEnvironment(environment.Name); subscription.SetTenant(accessToken.TenantId); tenant = new AzureTenant(); tenant.Id = accessToken.TenantId; tenant.Directory = accessToken.GetDomain(); return(true); } subscription = null; if (accessToken != null && accessToken.TenantId != null) { tenant = new AzureTenant(); tenant.Id = accessToken.TenantId; if (accessToken.UserId != null) { var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (domain.Length == 2) { tenant.Directory = domain[1]; } } return(true); } tenant = null; return(false); } }