public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } if (TokenProvider == null) { return new MockAccessToken() { AccessToken = account.Id, LoginType = LoginType.OrgId, UserId = account.Id }; } else { return TokenProvider(account, environment, tenant); } }
public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, TokenCache tokenCache, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { var configuration = GetAdalConfiguration(environment, tenant, resourceId, tokenCache); TracingAdapter.Information(Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); IAccessToken token; if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, account.Id, password, account.Type); } account.Id = token.UserId; return token; }
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; }
public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string clientId, string certificateThumbprint, AzureAccount.AccountType credentialType) { if (credentialType == AzureAccount.AccountType.User) { throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType"); } return new ServicePrincipalAccessToken(config, AcquireTokenWithCertificate(config, clientId, certificateThumbprint), (adalConfig, appId) => this.RenewWithCertificate(adalConfig, appId, certificateThumbprint), clientId); }
public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password, AzureAccount.AccountType credentialType) { if (credentialType == AzureAccount.AccountType.User) { throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType"); } return new ServicePrincipalAccessToken(config, AcquireTokenWithSecret(config, userId, password), this.RenewWithSecret, userId); }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { var configuration = GetAdalConfiguration(environment, tenant, resourceId); TracingAdapter.Information(Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); var token = TokenProvider.GetAccessToken(configuration, promptBehavior, account.Id, password, account.Type); account.Id = token.UserId; return token; }
public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string clientId, string certificate, AzureAccount.AccountType credentialType) { switch (credentialType) { case AzureAccount.AccountType.ServicePrincipal: return servicePrincipalTokenProvider.GetAccessTokenWithCertificate(config, clientId, certificate, credentialType); default: throw new ArgumentException(string.Format(Resources.UnsupportedCredentialType, credentialType), "credentialType"); } }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } return TokenProvider(account, environment, tenant); }
public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { return new HDInsightCertificateCredential { SubscriptionId = currentSubscription.Id, Certificate = AzureSession.DataStore.GetCertificate(currentSubscription.Account), Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement), }; }
public IAccessToken Authenticate( AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { return Authenticate(account, environment, tenant, password, promptBehavior, AzureSession.TokenCache, resourceId); }
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; }
public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password, AzureAccount.AccountType credentialType) { switch (credentialType) { case AzureAccount.AccountType.User: return userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType); case AzureAccount.AccountType.ServicePrincipal: return servicePrincipalTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType); default: throw new ArgumentException(Resources.UnknownCredentialType, "credentialType"); } }
public void ProfileSaveDoesNotSerializeContext() { var dataStore = new MockDataStore(); var currentProfile = new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)); AzureSession.DataStore = dataStore; var client = new ProfileClient(currentProfile); var tenant = 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, tenant } } }; var sub = new AzureSubscription { Account = account.Id, Environment = environment.Name, Id = new Guid(), Name = "Contoso Test Subscription", Properties = { { AzureSubscription.Property.Tenants, tenant } } }; client.AddOrSetEnvironment(environment); client.AddOrSetAccount(account); client.AddOrSetSubscription(sub); currentProfile.Save(); var profileFile = currentProfile.ProfilePath; string profileContents = dataStore.ReadFileAsText(profileFile); var readProfile = JsonConvert.DeserializeObject<Dictionary<string, object>>(profileContents); Assert.False(readProfile.ContainsKey("Context")); AzureProfile parsedProfile = new AzureProfile(); var serializer = new JsonProfileSerializer(); Assert.True(serializer.Deserialize(profileContents, parsedProfile)); Assert.NotNull(parsedProfile); Assert.NotNull(parsedProfile.Environments); Assert.True(parsedProfile.Environments.ContainsKey(environment.Name)); Assert.NotNull(parsedProfile.Accounts); Assert.True(parsedProfile.Accounts.ContainsKey(account.Id)); Assert.NotNull(parsedProfile.Subscriptions); Assert.True(parsedProfile.Subscriptions.ContainsKey(sub.Id)); }
public void SetupEnvironment() { base.SetupEnvironment(AzureModule.AzureResourceManager); TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); if (csmEnvironment.SubscriptionId != null) { //Overwrite the default subscription and default account //with ones using user ID and tenant ID from auth context var user = GetUser(csmEnvironment); var tenantId = GetTenantId(csmEnvironment); var testSubscription = new AzureSubscription() { Id = new Guid(csmEnvironment.SubscriptionId), Name = ProfileClient.Profile.DefaultSubscription.Name, Environment = ProfileClient.Profile.DefaultSubscription.Environment, Account = user, Properties = new Dictionary<AzureSubscription.Property, string> { {AzureSubscription.Property.Default, "True"}, { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT") }, {AzureSubscription.Property.Tenants, tenantId}, } }; var testAccount = new AzureAccount() { Id = user, Type = AzureAccount.AccountType.User, Properties = new Dictionary<AzureAccount.Property, string> { {AzureAccount.Property.Subscriptions, csmEnvironment.SubscriptionId}, } }; ProfileClient.Profile.Accounts.Remove(ProfileClient.Profile.DefaultSubscription.Account); ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription; ProfileClient.Profile.Accounts[testAccount.Id] = testAccount; ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account); ProfileClient.Profile.Save(); } }
// Gets the customer's Azure account and subscription information private static AzureProfile GetAzureProfile() { AzureProfile profile = new AzureProfile(); ProfileClient profileClient = new ProfileClient(profile); AzureAccount azureAccount = new AzureAccount() {Type = AzureAccount.AccountType.User}; // Prompts the user for their credentials and retrieves their account/subscription info profileClient.AddAccountAndLoadSubscriptions(azureAccount, profile.Environments[EnvironmentName.AzureCloud], null); // By default, the first subscription is chosen if (profileClient.Profile.Subscriptions.Count > 1) { SelectSubscription(profileClient.Profile); } return profileClient.Profile; }
public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior, AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } var token = new MockAccessToken { UserId = account.Id, LoginType = LoginType.OrgId, AccessToken = "123" }; return token; }
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()); } }
/// <summary> /// Create a new access token from the given account and tenant id /// </summary> /// <param name="account">The account, containing user id, access token information</param> /// <param name="tenantId">The tenant id for the given access token</param> /// <param name="tokenType">The token type for the given token.</param> public SimpleAccessToken(AzureAccount account, string tenantId, string tokenType = _defaultTokenType) { if (account == null) { throw new ArgumentNullException("account"); } if (string.IsNullOrWhiteSpace(account.Id)) { throw new ArgumentOutOfRangeException("account", Resources.AccessTokenRequiresAccount); } if (account.Type != AzureAccount.AccountType.AccessToken || !account.IsPropertySet(AzureAccount.Property.AccessToken)) { throw new ArgumentException(Resources.TypeNotAccessToken); } this.UserId = account.Id; this._tokenType = tokenType; this.AccessToken = account.GetProperty(AzureAccount.Property.AccessToken); this.TenantId = tenantId; }
public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment) { ProfileClient profileClient = new ProfileClient(new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile))); AzureContext azureContext = new AzureContext(currentSubscription, azureAccount, environment); var cloudCredentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(azureContext) as AccessTokenCredential; if (cloudCredentials != null) { var field= typeof(AccessTokenCredential).GetField("token", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance); var accessToken = field.GetValue(cloudCredentials) as IAccessToken; if (accessToken != null) { return new HDInsightAccessTokenCredential() { SubscriptionId = currentSubscription.Id, AccessToken = accessToken.AccessToken }; } } return null; }
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(); } } return result; }
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); } _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize(); return _profile; }
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)); 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, 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; } }
private IAccessToken AcquireAccessToken(AzureAccount account, AzureEnvironment environment, string tenantId, SecureString password, ShowDialog promptBehavior) { if (account.Type == AzureAccount.AccountType.AccessToken) { tenantId = tenantId ?? "Common"; return new SimpleAccessToken(account, tenantId); } return AzureSession.AuthenticationFactory.Authenticate( account, environment, tenantId, password, promptBehavior, TokenCache.DefaultShared); }
private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants) { List<AzureSubscription> result = new List<AzureSubscription>(); if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement)) { return result; } foreach (var tenant in tenants) { try { var tenantAccount = new AzureAccount(); CopyAccount(account, tenantAccount); var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never); if (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase)) { tenantAccount = account; } tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant }); using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>( new TokenCloudCredentials(tenantToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement))) { var subscriptionListResult = subscriptionClient.Subscriptions.List(); foreach (var subscription in subscriptionListResult.Subscriptions) { // only add the subscription if it's actually in this tenant if (subscription.ActiveDirectoryTenantId == tenant) { AzureSubscription psSubscription = new AzureSubscription { Id = new Guid(subscription.SubscriptionId), Name = subscription.SubscriptionName, Environment = environment.Name }; psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId); psSubscription.Account = tenantAccount.Id; tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions, new string[] { psSubscription.Id.ToString() }); result.Add(psSubscription); } } } AddOrSetAccount(tenantAccount); } catch (CloudException cEx) { WriteOrThrowAadExceptionMessage(cEx); } catch (AadAuthenticationException aadEx) { WriteOrThrowAadExceptionMessage(aadEx); } } return result; }
private void SetMockData() { azureSubscription1 = new AzureSubscription { Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub1", Environment = "Test", Account = "test", Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" } } }; azureSubscription2 = new AzureSubscription { Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub2", Environment = "Test", Account = "test" }; azureEnvironment = new AzureEnvironment { Name = "Test", Endpoints = new Dictionary<AzureEnvironment.Endpoint, string> { { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" }, { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" }, { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" }, { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" }, { AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, "vault-int.azure-int.net" }, { AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, "https://vault-int.azure-int.net/" }, } }; azureAccount = new AzureAccount { Id = "test", Type = AzureAccount.AccountType.User, Properties = new Dictionary<AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } } }; }
private IEnumerable<AzureSubscription> ListSubscriptionsForTenant(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string tenantId) { IAccessToken accessToken = null; try { accessToken = AcquireAccessToken(account, environment, tenantId, password, promptBehavior); } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenantId)); return new List<AzureSubscription>(); } using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>( new TokenCloudCredentials(accessToken.AccessToken), environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager))) { var subscriptions = subscriptionClient.Subscriptions.List(); if (subscriptions != null && subscriptions.Subscriptions != null) { return subscriptions.Subscriptions.Select( (s) => s.ToAzureSubscription(new AzureContext(_profile.Context.Subscription, account, environment, CreateTenantFromString(tenantId, accessToken.TenantId)))); } return new List<AzureSubscription>(); } }
private void ValidateCredential(PSCredential credential, AzureProfile profile, AzureAccount.AccountType accountType) { Assert.NotNull(profile.Accounts); Assert.NotNull(profile.Accounts.Values); Assert.Equal(profile.Accounts.Values.Count, 1); var account = profile.Accounts.Values.First(); Assert.Equal(account.Type, accountType); Assert.Equal(account.Id, credential.UserName); }
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; }
/// <summary> /// This overrides the default subscription and default account. This allows the /// test to get the tenant id in the test. /// </summary> public void SetupEnvironment() { base.SetupEnvironment(AzureModule.AzureResourceManager); TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment(); if (csmEnvironment.SubscriptionId != null) { //Overwrite the default subscription and default account //with ones using user ID and tenant ID from auth context var user = GetUser(csmEnvironment); var tenantId = GetTenantId(csmEnvironment); // Existing test will not have a user or tenant id set if (tenantId != null && user != null) { var testSubscription = new AzureSubscription() { Id = new Guid(csmEnvironment.SubscriptionId), Name = AzureRmProfileProvider.Instance.Profile.Context.Subscription.Name, Environment = AzureRmProfileProvider.Instance.Profile.Context.Subscription.Environment, Account = user, Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" }, { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT") }, { AzureSubscription.Property.Tenants, tenantId }, } }; var testAccount = new AzureAccount() { Id = user, Type = AzureAccount.AccountType.User, Properties = new Dictionary<AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, csmEnvironment.SubscriptionId }, } }; AzureRmProfileProvider.Instance.Profile.Context.Subscription.Name = testSubscription.Name; AzureRmProfileProvider.Instance.Profile.Context.Subscription.Id = testSubscription.Id; AzureRmProfileProvider.Instance.Profile.Context.Subscription.Account = testSubscription.Account; var environment = AzureRmProfileProvider.Instance.Profile.Environments[AzureRmProfileProvider.Instance.Profile.Context.Subscription.Environment]; environment.Endpoints[AzureEnvironment.Endpoint.Graph] = csmEnvironment.Endpoints.GraphUri.AbsoluteUri; environment.Endpoints[AzureEnvironment.Endpoint.StorageEndpointSuffix] = "core.windows.net"; AzureRmProfileProvider.Instance.Profile.Save(); } } }
private void CopyAccount(AzureAccount sourceAccount, AzureAccount targetAccount) { targetAccount.Id = sourceAccount.Id; targetAccount.Type = sourceAccount.Type; }