private AuthenticationParameters GetAuthenticationParameters(
            PowerShellTokenCacheProvider tokenCacheProvider,
            IAzureAccount account,
            IAzureEnvironment environment,
            string tenant,
            SecureString password,
            string promptBehavior,
            Action <string> promptAction,
            IAzureTokenCache tokenCache,
            string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            switch (account.Type)
            {
            case AzureAccount.AccountType.User:
                if (password == null)
                {
                    var homeAccountId = account.GetProperty(AzureAccount.Property.HomeAccountId) ?? "";

                    if (!string.IsNullOrEmpty(account.Id))
                    {
                        return(new SilentParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId));
                    }

                    if (account.IsPropertySet("UseDeviceAuth"))
                    {
                        return(new DeviceCodeParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId));
                    }
                    else if (account.IsPropertySet(AzureAccount.Property.UsePasswordAuth))
                    {
                        return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, homeAccountId));
                    }

                    return(new InteractiveParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId, promptAction));
                }

                return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, null));

            case AzureAccount.AccountType.Certificate:
            case AzureAccount.AccountType.ServicePrincipal:
                bool?sendCertificateChain    = null;
                var  sendCertificateChainStr = account.GetProperty(AzureAccount.Property.SendCertificateChain);
                if (!string.IsNullOrWhiteSpace(sendCertificateChainStr))
                {
                    sendCertificateChain = Boolean.Parse(sendCertificateChainStr);
                }
                password = password ?? ConvertToSecureString(account.GetProperty(AzureAccount.Property.ServicePrincipalSecret));
                var certificatePassword = ConvertToSecureString(account.GetProperty(AzureAccount.Property.CertificatePassword));
                return(new ServicePrincipalParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, account.GetProperty(AzureAccount.Property.CertificateThumbprint), account.GetProperty(AzureAccount.Property.CertificatePath),
                                                      certificatePassword, password, sendCertificateChain));

            case AzureAccount.AccountType.ManagedService:
                return(new ManagedServiceIdentityParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account));

            case AzureAccount.AccountType.AccessToken:
                return(new AccessTokenParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account));

            default:
                return(null);
            }
        }
예제 #2
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
        }
예제 #3
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
        }