Exemplo n.º 1
0
        public override void ExecuteCmdlet()
        {
            Guid   subscriptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscriptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
                if (SendCertificateChain)
                {
                    azureAccount.SetProperty("SendCertificateChain", SendCertificateChain.ToString());
                    WriteDebug("SendCertificateChain is set.");
                }
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                //ManagedServiceHostName/ManagedServicePort/ManagedServiceSecret are obsolete, should be removed in next major release
                if (this.IsBound(nameof(ManagedServiceHostName)) || this.IsBound(nameof(ManagedServicePort)) || this.IsBound(nameof(ManagedServiceSecret)))
                {
                    WriteWarning(Resources.ObsoleteManagedServiceParameters);
                }

                var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : envSecret;

                var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : envUri;

                if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) &&
                    !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret))
                {
                    // set flag indicating this is AppService Managed Identity ad hoc mode
                    azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used");
                }

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format(Constants.DefaultMsiAccountIdPrefix + "{0}", ManagedServicePort);
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities))
                {
                    commonUtilities = new CommonUtilities();
                    AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities);
                }
                if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication())
                {
                    WriteWarning(Resources.InteractiveAuthNotSupported);
                    return;
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    profileClient.DebugLog   = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();

                    try
                    {
                        //Must not use task.Result as it wraps inner exception into AggregateException
                        var result = (PSAzureProfile)task.GetAwaiter().GetResult();
                        WriteObject(result);
                    }
                    catch (AuthenticationFailedException ex)
                    {
                        if (IsUnableToOpenWebPageError(ex))
                        {
                            WriteWarning(Resources.InteractiveAuthNotSupported);
                            WriteDebug(ex.ToString());
                        }
                        else
                        {
                            if (IsUsingInteractiveAuthentication())
                            {
                                //Display only if user is using Interactive auth
                                WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
                            }
                            WriteDebug(ex.ToString());
                            throw;
                        }
                    }
                });
            }
        }
Exemplo n.º 2
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            AzureAccount azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                azureAccount.Id   = MyInvocation.BoundParameters.ContainsKey(nameof(AccountId))? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                var builder = new UriBuilder();
                builder.Scheme = "http";
                builder.Host   = ManagedServiceHostName;
                builder.Port   = ManagedServicePort;
                builder.Path   = "/oauth2/token";
                azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, builder.Uri.ToString());
                break;

            default:
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(TenantId))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { TenantId });
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    WriteObject((PSAzureProfile)profileClient.Login(
                                    azureAccount,
                                    _environment,
                                    TenantId,
                                    subscriptionId,
                                    subscriptionName,
                                    password,
                                    SkipValidation,
                                    (s) => WriteWarning(s),
                                    name));
                });
            }
        }
Exemplo n.º 3
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                break;

            default:
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

// TODO: Remove IfDef
#if NETSTANDARD
            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }
#endif

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    WriteObject((PSAzureProfile)profileClient.Login(
                                    azureAccount,
                                    _environment,
                                    Tenant,
                                    subscriptionId,
                                    subscriptionName,
                                    password,
                                    SkipValidation,
                                    WriteWarning,
                                    name,
                                    !SkipContextPopulation.IsPresent));
                });
            }
        }
Exemplo n.º 4
0
        public override void ExecuteCmdlet()
        {
            Guid   subscriptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscriptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            if (ClientAssertionParameterSet.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase))
            {
                string suppressWarningOrErrorValue = System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME);
                bool.TryParse(suppressWarningOrErrorValue, out bool suppressWarningOrError);
                if (!suppressWarningOrError)
                {
                    WriteWarning("The feature related to parameter name 'FederatedToken' is under preview.");
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalCertificateFileParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ClientAssertionParameterSet:
                azureAccount.Type = "ClientAssertion";
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                azureAccount.Id   = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}";
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrWhiteSpace(CertificatePath))
            {
                var resolvedPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(CertificatePath).FirstOrDefault()?.Path;
                if (string.IsNullOrEmpty(resolvedPath))
                {
                    var parametersLog = $"- Invalid certificate path :'{CertificatePath}'.";
                    throw new InvalidOperationException(parametersLog);
                }
                azureAccount.SetProperty(AzureAccount.Property.CertificatePath, resolvedPath);
                if (CertificatePassword != null)
                {
                    azureAccount.SetProperty(AzureAccount.Property.CertificatePassword, CertificatePassword.ConvertToString());
                }
            }

            if ((ParameterSetName == ServicePrincipalCertificateParameterSet || ParameterSetName == ServicePrincipalCertificateFileParameterSet) &&
                SendCertificateChain)
            {
                azureAccount.SetProperty(AzureAccount.Property.SendCertificateChain, SendCertificateChain.ToString());
                bool supressWarningOrError = false;
                try
                {
                    supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(BreakingChangeAttributeHelper.SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME));
                }
                catch
                {
                    //if value of env variable is invalid, use default value of supressWarningOrError
                }
                if (!supressWarningOrError)
                {
                    WriteWarning(Resources.PreviewFunctionMessage);
                }
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }
            if (azureAccount.Type == "ClientAssertion" && FederatedToken != null)
            {
                password = SecureStringExtensions.ConvertToSecureString(FederatedToken);
                azureAccount.SetProperty("ClientAssertion", FederatedToken);
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ClientAssertionWarning, file, directory));
                }
            }

            var resourceId = PreProcessAuthScope();

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                if (!AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out CommonUtilities commonUtilities))
                {
                    commonUtilities = new CommonUtilities();
                    AzureSession.Instance.RegisterComponent(nameof(CommonUtilities), () => commonUtilities);
                }
                if (!commonUtilities.IsDesktopSession() && IsUsingInteractiveAuthentication())
                {
                    WriteWarning(Resources.InteractiveAuthNotSupported);
                    return;
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    profileClient.DebugLog   = (message) => _tasks.Enqueue(new Task(() => this.WriteDebugWithTimestamp(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarningEvent, //Could not use WriteWarning directly because it may be in worker thread
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation,
                                                             resourceId));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();

                    try
                    {
                        //Must not use task.Result as it wraps inner exception into AggregateException
                        var result = (PSAzureProfile)task.GetAwaiter().GetResult();
                        WriteObject(result);
                    }
                    catch (AuthenticationFailedException ex)
                    {
                        if (IsUnableToOpenWebPageError(ex))
                        {
                            WriteWarning(Resources.InteractiveAuthNotSupported);
                            WriteDebug(ex.ToString());
                        }
                        else
                        {
                            if (IsUsingInteractiveAuthentication())
                            {
                                //Display only if user is using Interactive auth
                                WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
                            }
                            WriteDebug(ex.ToString());
                            throw;
                        }
                    }
                });
            }
        }
Exemplo n.º 5
0
        public override void ExecuteCmdlet()
        {
            Guid   subscrptionIdGuid;
            string subscriptionName = null;
            string subscriptionId   = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Subscription)))
            {
                if (Guid.TryParse(Subscription, out subscrptionIdGuid))
                {
                    subscriptionId = Subscription;
                }
                else
                {
                    subscriptionName = Subscription;
                }
            }

            var azureAccount = new AzureAccount();

            switch (ParameterSetName)
            {
            case AccessTokenParameterSet:
                azureAccount.Type = AzureAccount.AccountType.AccessToken;
                azureAccount.Id   = AccountId;
                azureAccount.SetProperty(AzureAccount.Property.AccessToken, AccessToken);
                azureAccount.SetProperty(AzureAccount.Property.GraphAccessToken, GraphAccessToken);
                azureAccount.SetProperty(AzureAccount.Property.KeyVaultAccessToken, KeyVaultAccessToken);
                break;

            case ServicePrincipalCertificateParameterSet:
            case ServicePrincipalParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ServicePrincipal;
                break;

            case ManagedServiceParameterSet:
                azureAccount.Type = AzureAccount.AccountType.ManagedService;
                var builder = new UriBuilder
                {
                    Scheme = "http",
                    Host   = ManagedServiceHostName,
                    Port   = ManagedServicePort,
                    Path   = "/oauth2/token"
                };

                var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable);

                var msiSecret = this.IsBound(nameof(ManagedServiceSecret))
                        ? ManagedServiceSecret.ConvertToString()
                        : envSecret;

                var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable);

                var suppliedUri = this.IsBound(nameof(ManagedServiceHostName))
                        ? builder.Uri.ToString()
                        : envUri;

                if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) &&
                    !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret))
                {
                    // set flag indicating this is AppService Managed Identity ad hoc mode
                    azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used");
                }

                if (!string.IsNullOrWhiteSpace(msiSecret))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret);
                }

                if (!string.IsNullOrWhiteSpace(suppliedUri))
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri);
                }
                else
                {
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString());
                    azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri);
                }

                azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format("MSI@{0}", ManagedServicePort);
                break;

            default:
                //Support username + password for both Windows PowerShell and PowerShell 6+
                azureAccount.Type = AzureAccount.AccountType.User;
                break;
            }

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (UseDeviceAuthentication.IsPresent)
            {
                azureAccount.SetProperty("UseDeviceAuth", "true");
            }

            if (azureAccount.Type == AzureAccount.AccountType.User && password != null)
            {
                azureAccount.SetProperty(AzureAccount.Property.UsePasswordAuth, "true");
            }

            if (!string.IsNullOrEmpty(ApplicationId))
            {
                azureAccount.Id = ApplicationId;
            }

            if (!string.IsNullOrWhiteSpace(CertificateThumbprint))
            {
                azureAccount.SetThumbprint(CertificateThumbprint);
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, Tenant);
            }

            if (azureAccount.Type == AzureAccount.AccountType.ServicePrincipal && string.IsNullOrEmpty(CertificateThumbprint))
            {
                azureAccount.SetProperty(AzureAccount.Property.ServicePrincipalSecret, password.ConvertToString());
                if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
                {
                    var file      = AzureSession.Instance.ARMProfileFile;
                    var directory = AzureSession.Instance.ARMProfileDirectory;
                    WriteWarning(string.Format(Resources.ServicePrincipalWarning, file, directory));
                }
            }

            if (ShouldProcess(string.Format(Resources.LoginTarget, azureAccount.Type, _environment.Name), "log in"))
            {
                if (AzureRmProfileProvider.Instance.Profile == null)
                {
                    InitializeProfileProvider();
                }

                SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
                {
                    bool shouldPopulateContextList = true;
                    if (this.IsParameterBound(c => c.SkipContextPopulation))
                    {
                        shouldPopulateContextList = false;
                    }

                    profileClient.WarningLog = (message) => _tasks.Enqueue(new Task(() => this.WriteWarning(message)));
                    var task = new Task <AzureRmProfile>(() => profileClient.Login(
                                                             azureAccount,
                                                             _environment,
                                                             Tenant,
                                                             subscriptionId,
                                                             subscriptionName,
                                                             password,
                                                             SkipValidation,
                                                             WriteWarning,
                                                             name,
                                                             shouldPopulateContextList,
                                                             MaxContextPopulation));
                    task.Start();
                    while (!task.IsCompleted)
                    {
                        HandleActions();
                        Thread.Yield();
                    }

                    HandleActions();
                    var result = (PSAzureProfile)(task.ConfigureAwait(false).GetAwaiter().GetResult());
                    WriteObject(result);
                });
            }
        }