Exemplo n.º 1
0
        public void VerifySubscriptionTokenCacheRemove()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "testuser",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("123");
            var sub = new AzureSubscription
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetTenant("123");
            var credential = authFactory.GetSubscriptionCloudCredentials(new AzureContext
                                                                         (
                                                                             sub,
                                                                             account,
                                                                             AzureEnvironment.PublicEnvironments["AzureCloud"]
                                                                         ));

            Assert.True(credential is AccessTokenCredential);
            Assert.Equal(subscriptionId, new Guid(((AccessTokenCredential)credential).SubscriptionId));
        }
        public void ProfileSerializeDeserializeWorks()
        {
            var dataStore   = new MockDataStore();
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ProfileFile);
            var profile     = new AzureSMProfile(profilePath);

            AzureSession.Instance.DataStore = dataStore;
            var tenant      = Guid.NewGuid().ToString();
            var environment = new AzureEnvironment
            {
                Name            = "testCloud",
                ActiveDirectory = new Uri("http://contoso.com")
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenant);
            var sub = new AzureSubscription
            {
                Id   = new Guid().ToString(),
                Name = "Contoso Test Subscription",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenant);

            profile.EnvironmentTable[environment.Name] = environment;
            profile.AccountTable[account.Id]           = account;
            profile.SubscriptionTable[sub.GetId()]     = sub;

            AzureSMProfile 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, profile);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                deserializedProfile = (AzureSMProfile)bf.Deserialize(ms);
            }
            Assert.NotNull(deserializedProfile);
            var jCurrentProfile      = JsonConvert.SerializeObject(profile);
            var jDeserializedProfile = JsonConvert.SerializeObject(deserializedProfile);

            Assert.Equal(jCurrentProfile, jDeserializedProfile);
        }
        public async Task ServicePrincipalCertificateFileWithSecretAuthenticationTest()
        {
            var accountId       = "testuser";
            var certificateFile = "d:/certficatefortest.pfx";
            var thumbprint      = Guid.NewGuid().ToString();
            var securePassword  = new SecureString();

            "pa88w0rd!".ToCharArray().ForEach(c => securePassword.AppendChar(c));

            IDataStore prevDataStore = AzureSession.Instance.DataStore;

            AzureSession.Instance.DataStore = new DiskDataStore();

            //Setup
            var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();

            mockAzureCredentialFactory.Setup(f => f.CreateClientCertificateCredential(
                                                 It.IsAny <string>(), It.IsAny <string>(), It.IsAny <X509Certificate2>(), It.IsAny <ClientCertificateCredentialOptions>())).Returns(() => new TokenCredentialMock());

            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
            InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();

            var account = new AzureAccount
            {
                Id   = accountId,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(TestTenantId);

            var parameter = new ServicePrincipalParameters(
                cacheProvider,
                AzureEnvironment.PublicEnvironments["AzureCloud"],
                null,
                TestTenantId,
                TestResourceId,
                account.Id,
                null,
                certificateFile,
                securePassword,
                null,
                null);

            //Run
            var authenticator = new ServicePrincipalAuthenticator();
            var token         = await authenticator.Authenticate(parameter);

            //Verify
            mockAzureCredentialFactory.Verify(f => f.CreateClientCertificateCredential(TestTenantId, accountId, It.IsAny <X509Certificate2>(), It.IsAny <ClientCertificateCredentialOptions>()), Times.Once());
            Assert.Equal(fakeToken, token.AccessToken);
            Assert.Equal(TestTenantId, token.TenantId);

            AzureSession.Instance.DataStore = prevDataStore;
        }
        public void ProfileSaveDoesNotSerializeContext()
        {
            var dataStore   = new MockDataStore();
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ProfileFile);
            var profile     = new AzureSMProfile(profilePath);

            AzureSession.Instance.DataStore = dataStore;
            var tenant      = Guid.NewGuid().ToString();
            var environment = new AzureEnvironment
            {
                Name            = "testCloud",
                ActiveDirectory = new Uri("http://contoso.com")
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenant);
            var sub = new AzureSubscription
            {
                Id   = new Guid().ToString(),
                Name = "Contoso Test Subscription",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenant);
            profile.EnvironmentTable[environment.Name] = environment;
            profile.AccountTable[account.Id]           = account;
            profile.SubscriptionTable[sub.GetId()]     = 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.EnvironmentTable.ContainsKey(environment.Name));
            Assert.NotNull(parsedProfile.Accounts);
            Assert.True(parsedProfile.AccountTable.ContainsKey(account.Id));
            Assert.NotNull(parsedProfile.Subscriptions);
            Assert.True(parsedProfile.SubscriptionTable.ContainsKey(sub.GetId()));
        }
Exemplo n.º 5
0
        public void VerifyUserAgentValuesAreTransmitted()
        {
            var storedClientFactory = AzureSession.Instance.ClientFactory;
            var storedAuthFactory   = AzureSession.Instance.AuthenticationFactory;

            try
            {
                var authFactory = new AuthenticationFactory();
                authFactory.TokenProvider = new MockAccessTokenProvider(Guid.NewGuid().ToString(), "*****@*****.**");
                AzureSession.Instance.AuthenticationFactory = authFactory;
                var factory = new ClientFactory();
                AzureSession.Instance.ClientFactory = factory;
                foreach (var agent in factory.UserAgents)
                {
                    factory.RemoveUserAgent(agent.Product.Name);
                }

                factory.AddUserAgent("agent1");
                factory.AddUserAgent("agent1", "1.0.0");
                factory.AddUserAgent("agent1", "1.0.0");
                factory.AddUserAgent("agent1", "1.9.8");
                factory.AddUserAgent("agent2");
                Assert.Equal(4, factory.UserAgents.Length);
                var sub = new AzureSubscription
                {
                    Id = Guid.NewGuid().ToString(),
                };
                sub.SetTenant("123");
                var account = new AzureAccount
                {
                    Id   = "*****@*****.**",
                    Type = AzureAccount.AccountType.User,
                };
                account.SetTenants("123");
                var client = factory.CreateClient <NullClient>(new AzureContext(
                                                                   sub,
                                                                   account,
                                                                   AzureEnvironment.PublicEnvironments["AzureCloud"]

                                                                   ), AzureEnvironment.Endpoint.ResourceManager);
                Assert.Equal(5, client.HttpClient.DefaultRequestHeaders.UserAgent.Count);
                Assert.Contains(new ProductInfoHeaderValue("agent1", ""), client.HttpClient.DefaultRequestHeaders.UserAgent);
                Assert.Contains(new ProductInfoHeaderValue("agent1", "1.0.0"), client.HttpClient.DefaultRequestHeaders.UserAgent);
                Assert.Contains(new ProductInfoHeaderValue("agent1", "1.9.8"), client.HttpClient.DefaultRequestHeaders.UserAgent);
                Assert.Contains(new ProductInfoHeaderValue("agent2", ""), client.HttpClient.DefaultRequestHeaders.UserAgent);
            }
            finally
            {
                AzureSession.Instance.ClientFactory         = storedClientFactory;
                AzureSession.Instance.AuthenticationFactory = storedAuthFactory;
            }
        }
        public async Task ServicePrincipalCertificateFileAuthenticationTest()
        {
            var accountId       = "testuser";
            var certificateFile = "d:/certficatefortest.pfx";

            IDataStore prevDataStore = AzureSession.Instance.DataStore;

            AzureSession.Instance.DataStore = new MockDataStore();
            AzureSession.Instance.DataStore.WriteFile(certificateFile, "dummyfile");

            //Setup
            var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();

            mockAzureCredentialFactory.Setup(f => f.CreateClientCertificateCredential(
                                                 It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ClientCertificateCredentialOptions>())).Returns(() => new TokenCredentialMock());

            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
            InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();

            var account = new AzureAccount
            {
                Id   = accountId,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(TestTenantId);

            var parameter = new ServicePrincipalParameters(
                cacheProvider,
                AzureEnvironment.PublicEnvironments["AzureCloud"],
                null,
                TestTenantId,
                TestResourceId,
                account.Id,
                null,
                certificateFile,
                null,
                null,
                null);

            //Run
            var authenticator = new ServicePrincipalAuthenticator();
            var token         = await authenticator.Authenticate(parameter);

            //Verify
            mockAzureCredentialFactory.Verify(f => f.CreateClientCertificateCredential(TestTenantId, accountId, certificateFile, It.IsAny <ClientCertificateCredentialOptions>()), Times.Once());
            Assert.Equal(fakeToken, token.AccessToken);
            Assert.Equal(TestTenantId, token.TenantId);

            AzureSession.Instance.DataStore = prevDataStore;
        }
        public void AddsAppropriateRetryPolicy()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string userAccount    = "*****@*****.**";
            Guid   subscriptionId = Guid.NewGuid();
            var    account        = new AzureAccount()
            {
                Id   = userAccount,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("common");
            var sub = new AzureSubscription()
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetAccount(userAccount);
            sub.SetEnvironment("AzureCloud");
            sub.SetTenant("common");
            AzureContext context = new AzureContext
                                   (
                sub,
                account,
                AzureEnvironment.PublicEnvironments["AzureCloud"]
                                   );

            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var factory = new ClientFactory();

            factory.AddHandler(new RetryTestHandler());
            var client      = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            var hyakHandler = EnsureHyakRetryPolicy(client);

            hyakHandler.MaxTries = 2;
            Assert.Throws <InvalidOperationException>(() => client.StorageAccounts.List());
            hyakHandler.MaxTries = 0;
            Assert.Throws <TaskCanceledException>(() => client.StorageAccounts.List());
            var autorestClient  = factory.CreateArmClient <ResourceManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager);
            var autoRestHandler = EnsureAutoRestRetryPolicy(autorestClient);

            autoRestHandler.MaxTries = 2;
            var task = autorestClient.ResourceGroups.ListWithHttpMessagesAsync();

            Assert.Throws <InvalidOperationException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult());
            autoRestHandler.MaxTries = 0;
            task = autorestClient.ResourceGroups.ListWithHttpMessagesAsync();
            Assert.Throws <TaskCanceledException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult());
        }
        public void VerifyClientFactoryWorks()
        {
            if (!runTest)
            {
                return;
            }
            var sub = new AzureSubscription()
            {
                Id = subscriptionId,
            };

            sub.SetAccount(userAccount);
            sub.SetEnvironment("AzureCloud");
            sub.SetTenant("common");
            var account = new AzureAccount()
            {
                Id   = userAccount,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("common");
            AzureContext context = new AzureContext
                                   (
                sub,
                account,
                AzureEnvironment.PublicEnvironments["AzureCloud"]
                                   );

            // Add registration action to make sure we register for the used provider (if required)
            // AzureSession.Instance.ClientFactory.AddAction(new RPRegistrationAction());

            // Authenticate!
            AzureSession.Instance.AuthenticationFactory.Authenticate(context.Account, context.Environment, "common", password, ShowDialog.Always, null);

            AzureSession.Instance.ClientFactory.AddUserAgent("TestUserAgent", "1.0");
            // Create the client
            var client = AzureSession.Instance.ClientFactory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);

            // List storage accounts
            var storageAccounts = client.StorageAccounts.List().StorageAccounts;

            foreach (var storageAccount in storageAccounts)
            {
                Assert.NotNull(storageAccount);
            }
        }
Exemplo n.º 9
0
        public void CanAuthenticateWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

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

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

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

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

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

            VerifyToken(checkKVToken, kvToken, userId, tenant);
            checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyToken(checkKVToken, kvToken, userId, tenant);
        }
        //Verify https://github.com/Azure/azure-powershell/issues/13376
        public async Task SystemAssignedMSI()
        {
            var accountId = Constants.DefaultMsiAccountIdPrefix + "12345";

            //Setup
            MockMsalAccessTokenAcquirer mockMsalAccessTokenAcquirer = SetupMockMsalAccessTokenAcquirer();

            var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();

            //id must be equal to null
            mockAzureCredentialFactory.Setup(f => f.CreateManagedIdentityCredential(It.Is <string>(id => id == null)))
            .Returns(new ManagedIdentityCredential(accountId));
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);

            var account = new AzureAccount
            {
                Id   = accountId,
                Type = AzureAccount.AccountType.ManagedService,
            };

            account.SetTenants(TestTenantId);

            InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();
            var parameter = new ManagedServiceIdentityParameters(
                cacheProvider,
                AzureEnvironment.PublicEnvironments["AzureCloud"],
                null,
                TestTenantId,
                TestResourceId,
                account);

            //Run
            ManagedServiceIdentityAuthenticator authenticator = new ManagedServiceIdentityAuthenticator();
            var token = await authenticator.Authenticate(parameter);

            //Verify
            var scopes = mockMsalAccessTokenAcquirer.TokenRequestContext.Scopes;

            Assert.True(scopes.Length == 1);
            Assert.Equal("https://management.core.windows.net/", scopes[0]);
            mockAzureCredentialFactory.Verify();
        }
Exemplo n.º 11
0
        public void DelegatingHandlersAreCloned()
        {
            AzureSessionInitializer.InitializeAzureSession();
            string userAccount    = "*****@*****.**";
            Guid   subscriptionId = Guid.NewGuid();
            var    account        = new AzureAccount()
            {
                Id   = userAccount,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("common");
            var sub = new AzureSubscription()
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetAccount(userAccount);
            sub.SetEnvironment("AzureCloud");
            sub.SetTenant("common");
            AzureContext context = new AzureContext
                                   (
                sub,
                account,
                AzureEnvironment.PublicEnvironments["AzureCloud"]
                                   );

            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(userAccount, Guid.NewGuid().ToString());
            var mockHandler = new MockDelegatingHandler();
            var factory     = new ClientFactory();

            factory.AddHandler(mockHandler);
            var client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);

            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            client = factory.CreateClient <StorageManagementClient>(context, AzureEnvironment.Endpoint.ServiceManagement);
            Assert.Equal(5, MockDelegatingHandler.cloneCount);
        }
Exemplo n.º 12
0
        public void VerifyValidateAuthorityFalseForOnPremise()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var authFactory = new AuthenticationFactory
            {
                TokenProvider = new MockAccessTokenProvider("testtoken", "testuser")
            };

            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "testuser",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants("123");
            var sub = new AzureSubscription
            {
                Id = subscriptionId.ToString(),
            };

            sub.SetTenant("123");
            var context = new AzureContext
                          (
                sub,
                account,
                new AzureEnvironment
            {
                Name      = "Katal",
                OnPremise = true,
                ActiveDirectoryAuthority = "http://ad.com",
                ActiveDirectoryServiceEndpointResourceId = "http://adresource.com"
            }
                          );

            var credential = authFactory.Authenticate(context.Account, context.Environment, "common", null, ShowDialog.Always, null);

            Assert.False(((MockAccessTokenProvider)authFactory.TokenProvider).AdalConfiguration.ValidateAuthority);
        }
Exemplo n.º 13
0
        public void CanGetServiceClientCredentialsWithAccessToken()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

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

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

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

            VerifyAccessTokenInServiceClientCredentials(credentials, armToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.Graph);
            VerifyAccessTokenInServiceClientCredentials(credentials, graphToken);
            credentials = authFactory.GetServiceClientCredentials(mockContext, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
            VerifyAccessTokenInServiceClientCredentials(credentials, kvToken);
        }
        public async Task SimpleSilentAuthenticationTest()
        {
            var accountId = "testuser";

            //Setup
            var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();

            mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock());
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
            InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();

            var account = new AzureAccount
            {
                Id   = accountId,
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(TestTenantId);

            var parameter = new SilentParameters(
                cacheProvider,
                AzureEnvironment.PublicEnvironments["AzureCloud"],
                null,
                TestTenantId,
                TestResourceId,
                account.Id,
                accountId);

            //Run
            var authenticator = new SilentAuthenticator();
            var token         = await authenticator.Authenticate(parameter);

            //Verify
            mockAzureCredentialFactory.Verify();
            Assert.Equal(fakeToken, token.AccessToken);
            Assert.Equal(TestTenantId, token.TenantId);
        }
        public void ProfileSerializeDeserializeWorks()
        {
            var dataStore = new MockDataStore();

            AzureSession.Instance.DataStore = dataStore;
            var profilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ProfileFile);
            var currentProfile = new AzureRmProfile(profilePath);
            var tenantId       = Guid.NewGuid().ToString();
            var environment    = new AzureEnvironment
            {
                Name = "testCloud",
                ActiveDirectoryAuthority = "http://contoso.com"
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenantId);
            var sub = new AzureSubscription
            {
                Id   = new Guid().ToString(),
                Name = "Contoso Test Subscription",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenantId);
            var tenant = new AzureTenant
            {
                Id        = tenantId,
                Directory = "contoso.com"
            };

            currentProfile.DefaultContext = new AzureContext(sub, account, environment, tenant);
            currentProfile.EnvironmentTable[environment.Name] = environment;
            currentProfile.DefaultContext.TokenCache          = new AzureTokenCache {
                CacheData = 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 override void ExecuteCmdlet()
        {
            IAzureAccount azureAccount = null;

            switch (ParameterSetName)
            {
            case UserIdParameterSet:
                azureAccount = new AzureAccount {
                    Id = Username, Type = AzureAccount.AccountType.User
                };
                break;

            case ServicePrincipalParameterSet:
                azureAccount = new AzureAccount {
                    Id = ApplicationId, Type = AzureAccount.AccountType.ServicePrincipal
                };
                azureAccount.SetTenants(TenantId);
                break;

            case InputObjectParametrSet:
                azureAccount = InputObject;
                break;

            case ContextParameterSet:
                azureAccount = AzureContext.Account;
                break;

            case ContextNameParameterSet:
                if (MyInvocation.BoundParameters.ContainsKey(nameof(ContextName)))
                {
                    var profile = DefaultProfile as AzureRmProfile;
                    azureAccount = profile.Contexts[ContextName].Account;
                }
                else
                {
                    azureAccount = DefaultContext?.Account;
                }
                break;
            }

            if (azureAccount == null || string.IsNullOrWhiteSpace(azureAccount.Id))
            {
                WriteExceptionError(new ArgumentException("Provide a valid account or context"));
            }
            else
            {
                if (ShouldProcess(string.Format("Log out principal '{0}'", azureAccount.Id), "log out"))
                {
                    if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                    {
                        AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, AzureSession.Instance.TokenCache);
                    }

                    if (AzureRmProfileProvider.Instance.Profile != null)
                    {
                        ModifyContext((localProfile, profileClient) =>
                        {
                            var matchingContexts = localProfile.Contexts?.Values?.Where((c) => c != null && c.Account != null && string.Equals(c.Account.Id, azureAccount.Id, StringComparison.CurrentCultureIgnoreCase));
                            foreach (var context in matchingContexts)
                            {
                                profileClient.TryRemoveContext(context);
                            }
                        });
                    }

                    WriteObject(new PSAzureRmAccount(azureAccount));
                }
            }
        }
        public void SavingProfileWorks()
        {
            string expected  = @"{
  ""EnvironmentTable"": {
    ""testCloud"": {
      ""Name"": ""testCloud"",
      ""OnPremise"": false,
      ""ServiceManagementUrl"": null,
      ""ResourceManagerUrl"": null,
      ""ManagementPortalUrl"": null,
      ""PublishSettingsFileUrl"": null,
      ""ActiveDirectoryAuthority"": ""http://contoso.com"",
      ""GalleryUrl"": null,
      ""GraphUrl"": null,
      ""ActiveDirectoryServiceEndpointResourceId"": null,
      ""StorageEndpointSuffix"": null,
      ""SqlDatabaseDnsSuffix"": null,
      ""TrafficManagerDnsSuffix"": null,
      ""AzureKeyVaultDnsSuffix"": null,
      ""AzureKeyVaultServiceEndpointResourceId"": null,
      ""GraphEndpointResourceId"": null,
      ""DataLakeEndpointResourceId"": null,
      ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null,
      ""AzureDataLakeStoreFileSystemEndpointSuffix"": null,
      ""AdTenant"": null,
      ""VersionProfiles"": [],
      ""ExtendedProperties"": {}
    }
  },
  ""Contexts"": {
    ""Default"": {
      ""Account"": {
        ""Id"": ""*****@*****.**"",
        ""Credential"": null,
        ""Type"": ""User"",
        ""TenantMap"": {},
        ""ExtendedProperties"": {
          ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
        }
      },
      ""Tenant"": {
        ""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
        ""Directory"": ""contoso.com"",
        ""ExtendedProperties"": {}
      },
      ""Subscription"": {
        ""Id"": ""00000000-0000-0000-0000-000000000000"",
        ""Name"": ""Contoso Test Subscription"",
        ""State"": ""Enabled"",
        ""ExtendedProperties"": {
          ""Account"": ""*****@*****.**"",
          ""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
          ""Environment"": ""testCloud""
        }
      },
      ""Environment"": {
        ""Name"": ""testCloud"",
        ""OnPremise"": false,
        ""ServiceManagementUrl"": null,
        ""ResourceManagerUrl"": null,
        ""ManagementPortalUrl"": null,
        ""PublishSettingsFileUrl"": null,
        ""ActiveDirectoryAuthority"": ""http://contoso.com"",
        ""GalleryUrl"": null,
        ""GraphUrl"": null,
        ""ActiveDirectoryServiceEndpointResourceId"": null,
        ""StorageEndpointSuffix"": null,
        ""SqlDatabaseDnsSuffix"": null,
        ""TrafficManagerDnsSuffix"": null,
        ""AzureKeyVaultDnsSuffix"": null,
        ""AzureKeyVaultServiceEndpointResourceId"": null,
        ""GraphEndpointResourceId"": null,
        ""DataLakeEndpointResourceId"": null,
        ""AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix"": null,
        ""AzureDataLakeStoreFileSystemEndpointSuffix"": null,
        ""AdTenant"": null,
        ""VersionProfiles"": [],
        ""ExtendedProperties"": {}
      },
      ""VersionProfile"": null,
      ""TokenCache"": {
        ""CacheData"": ""AgAAAAAAAAA=""
      },
      ""ExtendedProperties"": {}
    }
  },
  ""ExtendedProperties"": {}
}";
            var    path      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.Instance.ProfileFile);
            var    dataStore = new MockDataStore();

            AzureSession.Instance.DataStore = dataStore;
            AzureRmProfile profile     = new AzureRmProfile(path);
            var            tenantId    = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6");
            var            environment = new AzureEnvironment
            {
                Name = "testCloud",
                ActiveDirectoryAuthority = "http://contoso.com"
            };
            var account = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
            };

            account.SetTenants(tenantId.ToString());
            var sub = new AzureSubscription
            {
                Id    = new Guid().ToString(),
                Name  = "Contoso Test Subscription",
                State = "Enabled",
            };

            sub.SetAccount(account.Id);
            sub.SetEnvironment(environment.Name);
            sub.SetTenant(tenantId.ToString());
            var tenant = new AzureTenant
            {
                Id        = tenantId.ToString(),
                Directory = "contoso.com"
            };

            profile.DefaultContext = new AzureContext(sub, account, environment, tenant);
            profile.EnvironmentTable[environment.Name] = environment;
            profile.DefaultContext.TokenCache          = new AuthenticationStoreTokenCache(new AzureTokenCache {
                CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }
            });
            profile.Save();
            string actual = dataStore.ReadFileAsText(path);

            Assert.Equal(expected, actual);
        }