public static void Initialize()
        {
            AzureSession.Instance.DataStore         = new MemoryDataStore();
            AzureRmProfileProvider.Instance.Profile = new AzureRmProfile();

            PowerShellTokenCacheProvider tokenCacheProvider = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenCacheProvider);
            IAuthenticatorBuilder builder = new DefaultAuthenticatorBuilder();

            AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory());
            AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
        }
Пример #2
0
        private void InitializeSession()
        {
            AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore());
            AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
            PowerShellTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true);
            if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder))
            {
                builder = new DefaultAuthenticatorBuilder();
                AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
            }
            var profile = new AzureRmProfile
            {
                DefaultContext = defaultContext
            };

            cmdlet.profileClient = new RMProfileClient(profile);
        }
Пример #3
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);
        }
Пример #4
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);
        }
Пример #5
0
        public void CanAuthenticateUsingMSIObjectId()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

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

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for ARM URI: {0}", expectedAccessToken);
            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for graph URI: {0}", expectedToken2);
            string userId  = Guid.NewGuid().ToString();
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var defaultUri = builder.Uri.ToString();

            var customBuilder = new UriBuilder(AuthenticationFactory.DefaultMSILoginUri);

            customBuilder.Query = $"resource={Uri.EscapeDataString(environment.GraphEndpointResourceId)}&object_id={userId}&api-version=2018-02-01";
            var customUri = customBuilder.Uri.ToString();

            var responses = new Dictionary <string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            {
                { defaultUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource = expectedResource
                  } },
                { customUri, new ManagedServiceTokenInfo {
                      AccessToken = expectedToken2, ExpiresIn = 3600, Resource = environment.GraphEndpointResourceId
                  } }
            };

            AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true);
            var             authFactory = new AuthenticationFactory();
            IRenewableToken token       = (IRenewableToken)authFactory.Authenticate(account, environment, tenant, null, null, null);

            _output.WriteLine($"Received access token for default Uri ${token.AccessToken}");
            Assert.Equal(expectedAccessToken, token.AccessToken);
            Assert.Equal(3600, Math.Round(token.ExpiresOn.Subtract(DateTimeOffset.Now).TotalSeconds));
            var account2 = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, AzureEnvironment.Endpoint.GraphEndpointResourceId);

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");

            Assert.Throws <InvalidOperationException>(() => token3.AccessToken);
        }
Пример #6
0
        /// <summary>
        /// Load global aliases for ARM
        /// </summary>
        public void OnImport()
        {
#if DEBUG
            try
            {
#endif
            AzureSessionInitializer.InitializeAzureSession();
            AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings);
#if DEBUG
            if (!TestMockSupport.RunningMocked)
            {
#endif
            AzureSession.Instance.DataStore = new DiskDataStore();
#if DEBUG
        }
#endif

            var autoSaveEnabled  = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser;
            var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable);

            if (bool.TryParse(autosaveVariable, out bool localAutosave))
            {
                autoSaveEnabled = localAutosave;
            }

            try
            {
                if (autoSaveEnabled && !TokenCachePersistenceChecker.Verify())
                {
                    // If token cache persistence is not supported, fall back to plain text persistence, and print a warning
                    // We cannot just throw an exception here because this is called when importing the module
                    WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
                }
            }
            catch (Exception ex)
            {
                //Likely the exception is related permission, fall back context save mode to process
                autoSaveEnabled = false;
                AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
                WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
            }

            if (!InitializeProfileProvider(autoSaveEnabled))
            {
                AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
                autoSaveEnabled = false;
            }

            IServicePrincipalKeyStore keyStore =
                new AzureRmServicePrincipalKeyStore(AzureRmProfileProvider.Instance.Profile);
            AzureSession.Instance.RegisterComponent(ServicePrincipalKeyStore.Name, () => keyStore);

            IAuthenticatorBuilder builder = null;
            if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out builder))
            {
                builder = new DefaultAuthenticatorBuilder();
                AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
            }

            PowerShellTokenCacheProvider provider = null;
            if (autoSaveEnabled)
            {
                provider = new SharedTokenCacheProvider();
            }
            else     // if autosave is disabled, or the shared factory fails to initialize, we fallback to in memory
            {
                provider = new InMemoryTokenCacheProvider();
            }
            var tokenCache = provider.GetTokenCache();
            IAzureEventListenerFactory azureEventListenerFactory = new AzureEventListenerFactory();
            AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => new CommonUtilities());
            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => provider);
            AzureSession.Instance.RegisterComponent(nameof(IAzureEventListenerFactory), () => azureEventListenerFactory);
            AzureSession.Instance.RegisterComponent(nameof(PowerShellTokenCache), () => tokenCache);
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory());
            AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
#if DEBUG
        }
        catch (Exception) when(TestMockSupport.RunningMocked)
        {
            // This will throw exception for tests, ignore.
        }
#endif
        }
Пример #7
0
        /// <summary>
        /// Load global aliases for ARM
        /// </summary>
        public void OnImport()
        {
#if DEBUG
            try
            {
#endif
            AzureSessionInitializer.InitializeAzureSession();
            AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings);
#if DEBUG
            if (!TestMockSupport.RunningMocked)
            {
#endif
            AzureSession.Instance.DataStore = new DiskDataStore();
#if DEBUG
        }
#endif

            var autoSaveEnabled  = AzureSession.Instance.ARMContextSaveMode == ContextSaveMode.CurrentUser;
            var autosaveVariable = System.Environment.GetEnvironmentVariable(AzureProfileConstants.AzureAutosaveVariable);

            if (bool.TryParse(autosaveVariable, out bool localAutosave))
            {
                autoSaveEnabled = localAutosave;
            }

            try
            {
                if (autoSaveEnabled && !TokenCachePersistenceChecker.Verify())
                {
                    if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        // In Windows and macOS platforms, unknown errors are discovered that fails the persistence check.
                        // Disable context autosaving before msal library provide a fallback method for the case.
                        throw new PSInvalidOperationException(Resources.TokenCachePersistenceCheckError);
                    }
                    // If token cache persistence is not supported, fall back to plain text persistence, and print a warning
                    // We cannot just throw an exception here because this is called when importing the module
                    WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
                }
            }
            catch (Exception ex)
            {
                //Likely the exception is related permission, fall back context save mode to process
                autoSaveEnabled = false;
                AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
                WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
            }

            if (!InitializeProfileProvider(autoSaveEnabled))
            {
                AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
                autoSaveEnabled = false;
            }

#pragma warning disable CS0618 // Type or member is obsolete
            var keyStore = new AzKeyStore(AzureRmProfileProvider.Instance.Profile);
#pragma warning restore CS0618 // Type or member is obsolete
            AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore);

            IAuthenticatorBuilder builder = null;
            if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out builder))
            {
                builder = new DefaultAuthenticatorBuilder();
                AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
            }

            PowerShellTokenCacheProvider provider = null;
            if (autoSaveEnabled)
            {
                provider = new SharedTokenCacheProvider();
            }
            else     // if autosave is disabled, or the shared factory fails to initialize, we fallback to in memory
            {
                provider = new InMemoryTokenCacheProvider();
            }
            IAzureEventListenerFactory azureEventListenerFactory = new AzureEventListenerFactory();
            AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => new CommonUtilities());
            // It's tricky to register a component as an Interface
            // Make sure componentInitializer return the Interface, not the derived type
            AzureSession.Instance.RegisterComponent(nameof(ISharedUtilities), () => new AzureRmSharedUtilities() as ISharedUtilities);
            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => provider);
            AzureSession.Instance.RegisterComponent(nameof(IAzureEventListenerFactory), () => azureEventListenerFactory);
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory());
            AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
            AzureSession.Instance.RegisterComponent <ISshCredentialFactory>(nameof(ISshCredentialFactory), () => new SshCredentialFactory());
#if DEBUG
        }
        catch (Exception) when(TestMockSupport.RunningMocked)
        {
            // This will throw exception for tests, ignore.
        }
#endif
        }
        public void CanAuthenticateUsingMSIDefault()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAuthenticatorBuilder authenticatorBuilder = new DefaultAuthenticatorBuilder();

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

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => factory);
            var msalAccessTokenAcquirerFactory = new MsalAccessTokenAcquirerFactory();

            AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => msalAccessTokenAcquirerFactory, true);

            string expectedAccessToken = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for default URI: {0}", expectedAccessToken);
            var mockAzureCredentialFactory = new MockAzureCredentialFactory();
            MockManagedIdentityCredential mockManagedIdentityCredential = null;

            mockAzureCredentialFactory.CredentialFactory = (clientId) =>
            {
                return(mockManagedIdentityCredential = new MockManagedIdentityCredential(clientId)
                {
                    TokenFactory = () => new AccessToken(expectedAccessToken, DateTimeOffset.Now)
                });
            };
            AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => (AzureCredentialFactory)mockAzureCredentialFactory, true);

            string expectedToken2 = Guid.NewGuid().ToString();
            string tenant         = Guid.NewGuid().ToString();

            _output.WriteLine("Expected access token for custom URI: {0}", expectedToken2);
            string userId  = Constants.DefaultMsiAccountIdPrefix + "12345";
            var    account = new AzureAccount
            {
                Id   = userId,
                Type = AzureAccount.AccountType.ManagedService
            };
            var environment      = AzureEnvironment.PublicEnvironments["AzureCloud"];
            var expectedResource = environment.ActiveDirectoryServiceEndpointResourceId;
            var builder          = new UriBuilder(AuthenticationFactory.DefaultBackupMSILoginUri);
            //builder.Query = $"resource={Uri.EscapeDataString(environment.ActiveDirectoryServiceEndpointResourceId)}&api-version=2018-02-01";
            //var defaultUri = builder.Uri.ToString();

            //var responses = new Dictionary<string, ManagedServiceTokenInfo>(StringComparer.OrdinalIgnoreCase)
            //{
            //    {defaultUri, new ManagedServiceTokenInfo { AccessToken = expectedAccessToken, ExpiresIn = 3600, Resource=expectedResource}},
            //    {"http://*****:*****@foo.com";
            var account2 = new AzureAccount
            {
                Id   = userId2,
                Type = AzureAccount.AccountType.ManagedService
            };

            //account2.SetProperty(AzureAccount.Property.MSILoginUri, "http://myfunkyurl:10432/oauth2/token");
            expectedAccessToken = expectedToken2;
            var token2 = authFactory.Authenticate(account2, environment, tenant, null, null, null, "foo");

            _output.WriteLine($"Received access token for custom Uri ${token2.AccessToken}");
            Assert.Equal(expectedToken2, token2.AccessToken);
            Assert.Equal(userId2, mockManagedIdentityCredential.AccountId);
            //var token3 = authFactory.Authenticate(account, environment, tenant, null, null, null, "bar");
            //Assert.Throws<InvalidOperationException>(() => token3.AccessToken);
        }