Пример #1
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));
                });
            }
        }
Пример #2
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;
                        }
                    }
                });
            }
        }
Пример #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 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);
                });
            }
        }