Classes/VMWare.VCenter.psm1

using module .\VMWare.AuthType.psm1

class VMWareVCenter {
    [String]$VSphere
    [VMWareAuthType]$AuthType = [VMWareAuthType]::Integrated
    [PSCredential]$Credential
    [String]$ClientId
    [SecureString]$ClientSecret
    [Uri]$AuthorizationEndpointUrl
    [Uri]$TokenEndpointUrl
    [Uri]$RedirectUrl
    [String]$Scope
    [Bool]$IgnoreCertificateErrors

    # Establish a connection to this vCenter using its configured authentication mechanism.
    [Void] Connect() {
        try {
            if ($this.IgnoreCertificateErrors) {
                Write-Verbose 'Ignoring certificate errors for VSphere connection...'
                Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null
            }

            switch ($this.AuthType) {
                ([VMWareAuthType]::Credential) {
                    Write-Verbose 'Using provided credentials...'
                    Connect-VIServer -Server $this.VSphere -User $this.Credential.GetNetworkCredential().UserName -Password $this.Credential.GetNetworkCredential().Password -Force -ErrorAction Stop
                }
                ([VMWareAuthType]::SSO) {
                    Write-Verbose 'Using SSO (OAuth 2.0 -> SAML) authentication...'

                    $oauthParams = @{
                        ClientId                 = $this.ClientId
                        AuthorizationEndpointUrl = $this.AuthorizationEndpointUrl
                        TokenEndpointUrl         = $this.TokenEndpointUrl
                        RedirectUrl              = $this.RedirectUrl
                        ErrorAction              = 'Stop'
                    }
                    if ($this.Scope) { $oauthParams['Scope'] = $this.Scope }
                    if ($this.ClientSecret) { $oauthParams['ClientSecret'] = $this.ClientSecret }
                    if ($this.IgnoreCertificateErrors) { $oauthParams['IgnoreSslValidationErrors'] = $true }

                    $oauthContext = New-OAuthSecurityContext @oauthParams

                    $samlParams = @{
                        VCenterServer        = $this.VSphere
                        OAuthSecurityContext = $oauthContext
                        ErrorAction          = 'Stop'
                    }
                    if ($this.IgnoreCertificateErrors) { $samlParams['IgnoreSslValidationErrors'] = $true }

                    $samlContext = New-VISamlSecurityContext @samlParams

                    Connect-VIServer -Server $this.VSphere -SamlSecurityContext $samlContext -Force -ErrorAction Stop
                }
                default {
                    Write-Verbose 'No credentials provided, attempting to use current user context...'
                    Connect-VIServer -Server $this.VSphere -Force -ErrorAction Stop
                }
            }
        }
        catch {
            Write-Error $_
            throw 'Login Failed - See Error Above. Use Login-VSphere to re-authenticate.'
        }
    }
}