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 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()); } }
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; }
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); }
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; } }
public AzureRMProfile Login( AzureAccount account, AzureEnvironment environment, string tenantId, string subscriptionId, string subscriptionName, SecureString password) { AzureSubscription newSubscription = null; AzureTenant newTenant = null; ShowDialog promptBehavior = (password == null && account.Type != AzureAccount.AccountType.AccessToken && !account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) ? ShowDialog.Always : ShowDialog.Never; // (tenant and subscription are present) OR // (tenant is present and subscription is not provided) if (!string.IsNullOrEmpty(tenantId)) { var token = AcquireAccessToken(account, environment, tenantId, password, promptBehavior); if (TryGetTenantSubscription(token, account, environment, tenantId, subscriptionId, subscriptionName, out newSubscription, out newTenant)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, new[] { newTenant.Id.ToString() }); } } // (tenant is not provided and subscription is present) OR // (tenant is not provided and subscription is not provided) else { var tenants = ListAccountTenants(account, environment, password, promptBehavior).Select(s => s.Id.ToString()).ToArray(); account.SetProperty(AzureAccount.Property.Tenants, null); string accountId = null; for (int i = 0; i < tenants.Count(); i++) { var tenant = tenants[i]; AzureTenant tempTenant; AzureSubscription tempSubscription; IAccessToken token = null; try { token = AcquireAccessToken(account, environment, tenant, password, ShowDialog.Auto); if (accountId == null) { accountId = account.Id; account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase)) { account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant); } else { // if account ID is different from the first tenant account id we need to ignore current tenant WriteWarningMessage(string.Format( Microsoft.Azure.Commands.Profile.Properties.Resources.AccountIdMismatch, account.Id, tenant, accountId)); account.Id = accountId; token = null; } } catch { WriteWarningMessage(string.Format(Microsoft.Azure.Commands.Profile.Properties.Resources.UnableToAqcuireToken, tenant)); } if (token != null && newTenant == null && TryGetTenantSubscription(token, account, environment, tenant, subscriptionId, subscriptionName, out tempSubscription, out tempTenant)) { // If no subscription found for the given token/tenant // discard tempTenant value unless current token/tenant is the last one. if (tempSubscription != null || i == (tenants.Count() - 1)) { newTenant = tempTenant; newSubscription = tempSubscription; } } } } if (newSubscription == null) { if (subscriptionId != null) { throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionIdNotFound, account.Id, subscriptionId)); } else if (subscriptionName != null) { throw new PSInvalidOperationException(String.Format(Properties.Resources.SubscriptionNameNotFound, account.Id, subscriptionName)); } _profile.Context = new AzureContext(account, environment, newTenant); } else { _profile.Context = new AzureContext(newSubscription, account, environment, newTenant); if (!newSubscription.State.Equals("Enabled", StringComparison.OrdinalIgnoreCase)) { WriteWarningMessage(string.Format( Microsoft.Azure.Commands.Profile.Properties.Resources.SelectedSubscriptionNotActive, newSubscription.State)); } } _profile.Context.TokenCache = TokenCache.DefaultShared.Serialize(); return _profile; }
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 }); } 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)); }
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(); } }
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(); } }
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; } }