public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
 {
     Subscription = subscription;
     Account = account;
     Environment = environment;
     Tenant = tenant;
 }
        /// <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();
                }
            }
        }
        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 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 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 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 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 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 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 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 void ProfileSaveDoesNotSerializeContext()
        {
            var dataStore = new MockDataStore();
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var profile = new AzureSMProfile(profilePath);
            AzureSession.DataStore = dataStore;
            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 } }
            };

            profile.Environments[environment.Name] = environment;
            profile.Accounts[account.Id] = account;
            profile.Subscriptions[sub.Id] = sub;

            profile.Save();

            var profileFile = profile.ProfilePath;
            string profileContents = dataStore.ReadFileAsText(profileFile);
            var readProfile = JsonConvert.DeserializeObject<Dictionary<string, object>>(profileContents);
            Assert.False(readProfile.ContainsKey("DefaultContext"));
            AzureSMProfile parsedProfile = new AzureSMProfile();
            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));
        }
Exemple #13
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    AzureAccount azureAccount = new AzureAccount();
                    azureAccount.Type = AzureAccount.AccountType.User;

                    var environment = AzureEnvironment.PublicEnvironments["AzureCloud"];

                    var auth = new Authenticator(AzureRmProfileProvider.Instance.Profile);
                    auth.Login(azureAccount, environment);
                }
                else if (args.Length == 2)
                {
                    var subcriptionId = args[0];
                    var authToken = args[1];

                    Authenticator.ShowIoTHubsInSubscription(subcriptionId, authToken).Wait();
                }
                else
                {
                    Console.WriteLine("Usage:");
                    Console.WriteLine("MSAAuthenticator.exe");
                    Console.WriteLine("    Pop up a credentials gatheting windows and list all IoT Hubs under all subscriptions associated with the user");
                    Console.WriteLine("MSAAuthenticator.exe <subscription_id> <access_token>");
                    Console.WriteLine("    Lists IoT Hubs abd devices given subscription_id and access_token");
                }
            }
            catch (Exception ex)
            {
                var aggr = ex as System.AggregateException;
                if (aggr != null)
                {
                    foreach (var inner in aggr.InnerExceptions)
                    {
                        Console.WriteLine("Exception: {0}", inner.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Exception: {0}", ex.Message);
                }
            }
        }
 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 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());
            } 
        }
        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 = AzureRmProfileProvider.Instance.Profile.Context.Subscription.Name,
                    Environment = AzureRmProfileProvider.Instance.Profile.Context.Environment.Name,
                    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 = new AzureContext(testSubscription, testAccount, AzureRmProfileProvider.Instance.Profile.Context.Environment, new AzureTenant { Id = new Guid(tenantId) });
            }
        }
 /// <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 AzureSMProfile(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;
        }
        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";
            }

            var token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = "123"
            };

            return token;
        }
        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>
        /// Creates new instance of AzureContext.
        /// </summary>
        /// <param name="account">The azure account object</param>
        /// <param name="environment">The azure environment object</param>
        /// <param name="tenant">The azure tenant object</param>
        public AzureContext(AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
            : this(null, account, environment, tenant)
        {

        }
        public void NewProfileFromADWithMismatchSubscriptionThrows()
        {
            SetMocks(new[] { rdfeSubscription1, rdfeSubscription2 }.ToList(), new[] { csmSubscription1 }.ToList());
            MemoryDataStore dataStore = new MemoryDataStore();
            AzureSession.DataStore = dataStore;
            AzureSMProfile newProfile = new AzureSMProfile();
            ProfileClient client1 = new ProfileClient(newProfile);
            var newAccount = new AzureAccount { Id = "foo" };
            newAccount.Properties[AzureAccount.Property.Tenants] = "123";

            Assert.Throws<ArgumentException>(() => client1.InitializeProfile(AzureEnvironment.PublicEnvironments["AzureCloud"],
                Guid.NewGuid(), newAccount, null, null));
        }
        private void SetMockData()
        {
            commonTenant = new TenantIdDescription
            {
                Id = "Common",
                TenantId = "Common"
            };
            guestTenant = new TenantIdDescription
            {
                Id = "Guest",
                TenantId = "Guest"
            };
            rdfeSubscription1 = new RDFESubscription
            {
                SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                SubscriptionName = "RdfeSub1",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active,
                ActiveDirectoryTenantId = "Common"
            };
            rdfeSubscription2 = new RDFESubscription
            {
                SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                SubscriptionName = "RdfeSub2",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Warned,
                ActiveDirectoryTenantId = "Common"
            };
            guestRdfeSubscription = new RDFESubscription
            {
                SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1C",
                SubscriptionName = "RdfeSub2",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active,
                ActiveDirectoryTenantId = "Guest"
            };
            csmSubscription1 = new CSMSubscription
            {
                Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "CsmSub1",
                State = "Active",
                SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            csmSubscription1withDuplicateId = new CSMSubscription
            {
                Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "RdfeSub1",
                State = "Active",
                SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            csmSubscription2 = new CSMSubscription
            {
                Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "CsmSub2",
                State = "Active",
                SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            guestCsmSubscription = new CSMSubscription
            {
                Id = "Subscriptions/76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D",
                DisplayName = "CsmGuestSub",
                State = "Active",
                SubscriptionId = "76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D"
            };
            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"
            };
            azureSubscription3withoutUser = new AzureSubscription
            {
                Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
                Name = "LocalSub3",
                Environment = "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/" },
                }
            };
            azureAccount = new AzureAccount
            {
                Id = "test",
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string>
                {
                    { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
                }
            };
            newProfileDataPath = Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile);
            oldProfileDataPath = Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFile);
            oldProfileDataPathError = Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFileBackup);
            oldProfileData = @"<?xml version=""1.0"" encoding=""utf-8""?>
                <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Authentication"">
                  <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
                  <Environments>
                    <AzureEnvironmentData>
                      <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
                      <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
                      <CommonTenantId>Common</CommonTenantId>
                      <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint>
                      <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl>
                      <Name>Current</Name>
                      <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl>
                      <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint>
                      <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint>
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <StorageEndpointSuffix i:nil=""true"" />
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureEnvironmentData>
                    <AzureEnvironmentData>
                      <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
                      <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
                      <CommonTenantId>Common</CommonTenantId>
                      <GalleryEndpoint>https://df.gallery.azure-test.net</GalleryEndpoint>
                      <ManagementPortalUrl>https://windows.azure-test.net</ManagementPortalUrl>
                      <Name>Dogfood</Name>
                      <PublishSettingsFileUrl>https://auxnext.windows.azure-test.net/publishsettings/index</PublishSettingsFileUrl>
                      <ResourceManagerEndpoint>https://api-dogfood.resources.windows-int.net</ResourceManagerEndpoint>
                      <ServiceEndpoint>https://management-preview.core.windows-int.net/</ServiceEndpoint>
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <StorageEndpointSuffix i:nil=""true"" />
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureEnvironmentData>
                  </Environments>
                  <Subscriptions>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId i:nil=""true"" />
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
                      <Name>Test</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId>123</ActiveDirectoryTenantId>
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint>https://management-preview.core.windows-int.net/</ManagementEndpoint>
                      <Name>Test 2</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint>
                      <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
                      <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId>
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>false</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
                      <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
                      <Name>Test 3</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId i:nil=""true"" />
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>false</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
                      <ManagementEndpoint>https://management.core.chinacloudapi.cn/</ManagementEndpoint>
                      <Name>Mooncake Test</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>c14d7dc5-ed4d-4346-a02f-9f1bcf78fb66</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                  </Subscriptions>
                </ProfileData>";

            oldProfileDataBadSubscription = @"<?xml version=""1.0"" encoding=""utf-8""?>
                <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Authentication"">
                  <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
                  <Environments>                    
                  </Environments>
                  <Subscriptions>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId i:nil=""true"" />
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
                      <Name>Test Nill ID</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId i:nil=""true"" />
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint>Bad Data</ManagementEndpoint>
                      <Name>Test Bad Management Endpoint</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint i:nil=""true""/>
                      <Name>Test Null Management Endpoint</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2ADFF</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint>
                      <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
                      <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId>
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>false</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E99</ManagementCertificate>
                      <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
                      <Name>Test Bad Cert</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId>
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>                    
                  </Subscriptions>
                </ProfileData>";

            oldProfileDataCorruptedFile = @"<?xml version=""1.0"" encoding=""utf-8""?>
                <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Authentication"">
                  <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
                  <Environments bad>
                    <AzureEnvironmentData>
                      <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
                      <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
                      <CommonTenantId>Common</CommonTenantId>
                      <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint>
                      <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl>
                      <Name>Current</Name>
                      <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl>
                      <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint>
                      <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint>
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <StorageEndpointSuffix i:nil=""true"" />
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureEnvironmentData>
                  <Subscriptions>                    
                  </Subscriptions>
                </ProfileData>";
        }
        public void NewProfileFromADReturnsProfile()
        {
            SetMocks(new[] { rdfeSubscription1, rdfeSubscription2 }.ToList(), new List<CSMSubscription>());
            rdfeSubscription2.ActiveDirectoryTenantId = "123";
            MemoryDataStore dataStore = new MemoryDataStore();
            AzureSession.DataStore = dataStore;
            AzureSMProfile newProfile = new AzureSMProfile();
            ProfileClient client1 = new ProfileClient(newProfile);
            var newAccount = new AzureAccount { Id = "foo" };
            newAccount.Properties[AzureAccount.Property.Tenants] = "123";

            client1.InitializeProfile(AzureEnvironment.PublicEnvironments["AzureCloud"],
                new Guid(rdfeSubscription2.SubscriptionId), newAccount, null, null);

            Assert.Equal("AzureCloud", newProfile.DefaultSubscription.Environment);
            Assert.Equal(new Guid(rdfeSubscription2.SubscriptionId), newProfile.DefaultSubscription.Id);
            Assert.Equal(newAccount.Id, newProfile.DefaultSubscription.Account);
            Assert.False(newProfile.DefaultSubscription.Properties.ContainsKey(AzureSubscription.Property.StorageAccount));
        }
Exemple #25
0
 /// <summary>
 /// Creates new instance of AzureContext.
 /// </summary>
 /// <param name="account">The azure account object</param>
 /// <param name="environment">The azure environment object</param>
 /// <param name="tenant">The azure tenant object</param>
 public AzureContext(AzureAccount account, AzureEnvironment environment, AzureTenant tenant)
     : this(null, account, environment, tenant)
 {
 }
 /// <summary>
 /// Creates new instance of AzureContext.
 /// </summary>
 /// <param name="subscription">The azure subscription object</param>
 /// <param name="account">The azure account object</param>
 /// <param name="environment">The azure environment object</param>
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment) 
     : this(subscription, account, environment, null)
 {
     
 }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
 private void CopyAccount(AzureAccount sourceAccount, AzureAccount targetAccount)
 {
     targetAccount.Id = sourceAccount.Id;
     targetAccount.Type = sourceAccount.Type;
 }
Exemple #29
0
        public void RefreshContextsFromCache()
        {
            // Authentication factory is already registered in `OnImport()`
            AzureSession.Instance.TryGetComponent(
                PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey,
                out PowerShellTokenCacheProvider tokenCacheProvider);

            string authority = null;

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

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

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

                    removedContext |= TryCacheRemoveContext(contextName);
                }

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

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

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

                    updatedContext |= TryCacheRemoveContext(contextName);
                }

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

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

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

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

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

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

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

            Save(ProfilePath, false);
        }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment = subscription.Environment;
            }
            else
            {
                subscription = new AzureSubscription();
                subscription.Id = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            if (environment == null)
            {
                var profileClient = new ProfileClient(Profile);
                environment = profileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not "+
                    "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This "+
                    "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName) || Context != null)
            {
                ProfileClient.GetAccount(subscription.Account);
                if (Profile.Context != null && Profile.Context.Subscription != null &&
                    Profile.Context.Subscription.Id == subscription.Id)
                {
                    GeneralUtilities.ClearCurrentStorageAccount();
                }
                var context = new AzureContext(subscription, ProfileClient.GetAccount(subscription.Account), ProfileClient.GetEnvironmentOrDefault(subscription.Environment));
                if (Context != null)
                {
                    context.SetCurrentStorageAccount(this);
                }
                else
                {
                    var client = AzureSession.ClientFactory.CreateClient<StorageManagementClient>(context,
                        AzureEnvironment.Endpoint.ServiceManagement);
                    var account = StorageUtilities.GenerateCloudStorageAccount(client, CurrentStorageAccountName);
                    context.SetCurrentStorageAccount(account.ToString(true));
                }
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
        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;
        }
 public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string principalId, string certificateThumbprint, AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
Exemple #33
0
 /// <summary>
 /// Creates new instance of AzureContext.
 /// </summary>
 /// <param name="subscription">The azure subscription object</param>
 /// <param name="account">The azure account object</param>
 /// <param name="environment">The azure environment object</param>
 public AzureContext(AzureSubscription subscription, AzureAccount account, AzureEnvironment environment)
     : this(subscription, account, environment, null)
 {
 }