PSOAuthHelper.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = '0.3.1'

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName PSOAuthHelper.Import.DoDotSource -Fallback $false
if ($PSOAuthHelper_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName PSOAuthHelper.Import.IndividualFiles -Fallback $false
if ($PSOAuthHelper_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    if ($doDotSource) { . (Resolve-Path $Path) }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText((Resolve-Path $Path)))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'PSOAuthHelper' -Language 'en-US'


<#
    .SYNOPSIS
        Convert HashTable into an array
         
    .DESCRIPTION
        Convert HashTable with switches inside into an array of Key:Value
         
    .PARAMETER InputObject
        The HashTable object that you want to work against
         
        Shold only contain Key / Vaule, where value is $true or $false
         
    .PARAMETER KeyPrefix
        The prefix that you want to append to the key of the HashTable
         
        The default value is "-"
         
    .PARAMETER ValuePrefix
        The prefix that you want to append to the value of the HashTable
         
        The default value is ":"
         
    .PARAMETER KeepCase
        Instruct the cmdlet to keep the naming case of the properties from the hashtable
         
        Default value is: $true
         
    .EXAMPLE
        PS C:\> $params = @{NoPrompt = $true; CreateParents = $false}
        PS C:\> $arguments = Convert-HashToArgStringSwitch -Inputs $params
         
        This will convert the $params into an array of strings, each with the "-Key:Value" pattern.
         
    .EXAMPLE
        PS C:\> $params = @{NoPrompt = $true; CreateParents = $false}
        PS C:\> $arguments = Convert-HashToArgStringSwitch -InputObject $params -KeyPrefix "&" -ValuePrefix "="
         
        This will convert the $params into an array of strings, each with the "&Key=Value" pattern.
         
    .NOTES
        Tags: HashTable, Arguments
         
        Author: Mötz Jensen (@Splaxi)
         
#>


function Convert-HashToArgStringSwitch {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueSwitchParameter", "")]
    [CmdletBinding()]
    [OutputType([System.String])]
    param (
        [HashTable] $InputObject,

        [string] $KeyPrefix = "-",

        [string] $ValuePrefix = ":",

        [switch] $KeepCase = $true
    )

    foreach ($key in $InputObject.Keys) {
        $value = "{0}" -f $InputObject.Item($key).ToString()
        if (-not $KeepCase) { $value = $value.ToLower() }
        "$KeyPrefix$($key)$ValuePrefix$($value)"
    }
}


<#
    .SYNOPSIS
        Clone a hashtable
         
    .DESCRIPTION
        Create a deep clone of a hashtable for you to work on it without updating the original object
         
    .PARAMETER InputObject
        The hashtable you want to clone
         
    .EXAMPLE
        PS C:\> Get-DeepClone -InputObject $HashTable
         
        This will clone the $HashTable variable into a new object and return it to you.
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>

function Get-DeepClone {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseOutputTypeCorrectly', '')]
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $true)]
        $InputObject
    )
    process
    {
        if($InputObject -is [hashtable]) {

            $clone = @{}

            foreach($key in $InputObject.keys)
            {
                $clone[$key] = Get-DeepClone $InputObject[$key]
            }

            $clone
        } else {
            $InputObject
        }
    }
}


<#
    .SYNOPSIS
        Invoke an OAuth 2.0 authorization request
         
    .DESCRIPTION
        Invoke an OAuth 2.0 grant type flow request
         
    .PARAMETER AuthProviderUri
        The URL / URI for the authorization server
         
    .PARAMETER Resource
        The URL / URI for the protected resource you want the token to be valid to
         
    .PARAMETER GrantType
        The OAuth flow you want to utilize
         
        Valid Options:
        Authorization Code
        Implicit
        Password
        Client Credentials
        Device Code
        Refresh Token
         
    .PARAMETER ClientId
        The Client Id that you want to use for the authentication process
         
    .PARAMETER ClientSecret
        The Client Secret that you want to use for the authentication process
         
    .PARAMETER Username
        Username for the user that you want to authenticate as
         
    .PARAMETER Password
        Password for the user that you want to authenticate as
         
    .PARAMETER Scope
        The scope details that you want the token to valid for
         
    .PARAMETER RefreshToken
        The Refresh Token that you want to use for the authentication process
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Invoke-Authorization -AuthProviderUri "https://login.microsoftonline.com/e674da86-7ee5-40a7-b777-1111111111111/oauth2/token" -Resource "https://www.superfantasticservername.com" -GrantType "client_credentials" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -ClientSecret "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522="
         
        This will invoke an OAuth Client Credentials Grant flow against Azure Active Directory for the tenant id "e674da86-7ee5-40a7-b777-1111111111111".
        The token will be valid for the "https://www.superfantasticservername.com" resource.
        The ClientId is "dea8d7a9-1602-4429-b138-111111111111".
        The ClientSecret is "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522="
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>


function Invoke-Authorization {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "")]
    [CmdletBinding()]
    [OutputType('System.String')]
    param (
        [Parameter(Mandatory = $true)]
        [string] $AuthProviderUri,

        [string] $Resource,

        [string] $GrantType,

        [string] $ClientId,

        [string] $ClientSecret,

        [string] $Username,

        [string] $Password,

        [string] $Scope,

        [string] $RefreshToken,

        [switch] $EnableException
    )


    $parms = @{}
    $parms.grant_type = [System.Uri]::EscapeDataString($GrantType)
    
    if (-not ($Resource -eq "")) {$parms.resource = [System.Uri]::EscapeDataString($Resource)}
    
    if (-not ($ClientId -eq "")) {$parms.client_id = [System.Uri]::EscapeDataString($ClientId)}

    if (-not ($ClientSecret -eq "")) {$parms.client_secret = [System.Uri]::EscapeDataString($ClientSecret)}

    if (-not ($Username -eq "")) {$parms.username = [System.Uri]::EscapeDataString($Username)}

    if (-not ($Password -eq "")) {$parms.password = [System.Uri]::EscapeDataString($Password)}

    if (-not ($Scope -eq "")) {$parms.scope = [System.Uri]::EscapeDataString($Scope)}

    if (-not ($RefreshToken -eq "")) {$parms.refresh_token = [System.Uri]::EscapeDataString($RefreshToken)}
    

    $body = (Convert-HashToArgStringSwitch -InputObject $parms -KeyPrefix "&" -ValuePrefix "=") -join ""

    $body = $body.Substring(1)

    Write-PSFMessage -Level Verbose -Message "Authenticating against Azure Active Directory (AAD)." -Target $body

    try {
        $requestParams = @{Method = "Post"; ContentType = "application/x-www-form-urlencoded";
                    Body = $body}

        $Authorization = Invoke-RestMethod $AuthProviderUri @requestParams
    }
    catch {
        Write-PSFMessage -Level Host -Message "Something went wrong while working against Azure Active Directory (AAD)" -Exception $PSItem.Exception -Target $body
        Stop-PSFFunction -Message "Stopping because of errors" -StepsUpward 1
        return
    }

    $Authorization
}


<#
    .SYNOPSIS
        Get a bearer token string
         
    .DESCRIPTION
        Easy way to create a bearer token string from a object
         
    .PARAMETER InputObject
        The object you received from any of the Invoke-* commands that returns an access token
         
    .PARAMETER Raw
        Instruct the cmdlets to return just the token value as a raw string
         
    .EXAMPLE
        PS C:\> Invoke-ClientCredentialsGrant -AuthProviderUri "https://login.microsoftonline.com/e674da86-7ee5-40a7-b777-1111111111111/oauth2/token" -Resource "https://www.superfantasticservername.com" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -ClientSecret "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522=" | Get-BearerToken
         
        This will run the Invoke-ClientCredentialsGrant cmdlet with all the needed parameters.
        Then it will pass the output to the Get-BearerToken through the pipeline.
         
    .LINK
        Invoke-ClientCredentialsGrant
         
    .LINK
        Invoke-PasswordGrant
         
    .LINK
        Invoke-RefreshToken
         
    .NOTES
        Tags: BearerToken, Token, AccessToken, Bearer
         
        Author: Mötz Jensen (@Splaxi)
#>


function Get-BearerToken {
    [CmdletBinding()]
    [OutputType('System.String')]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 1)]
        [PSCustomObject] $InputObject,

        [switch] $Raw
    )

    process {
        if ($Raw) {
            $($InputObject.access_token)
        }
        else {
            "Bearer $($InputObject.access_token)"
        }
    }
}


<#
    .SYNOPSIS
        Get how many minutes there is left of on token
         
    .DESCRIPTION
        Pass the token object directly into the cmdlet and see how many minutes are left before the token expires
         
    .PARAMETER InputObject
        The object you received from any of the Invoke-* commands that returns an access token
         
    .EXAMPLE
        PS C:\> Get-RemainingMinutes -InputObject $TokenObject
         
        This will analyse the expires_on and compare it with NOW, to see how many minutes there is left before the token will be expired.
         
    .LINK
        Invoke-ClientCredentialsGrant
         
    .LINK
        Invoke-PasswordGrant
         
    .LINK
        Invoke-RefreshToken
         
    .NOTES
        Tags: Token, Expiration, Expire
         
        Author: Mötz Jensen (@Splaxi)
#>


function Get-RemainingMinutes {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "")]
    [CmdletBinding()]
    [OutputType('System.Int32')]
    param (
        [Parameter(Mandatory = $true, Position = 1)]
        [PSCustomObject] $InputObject
    )

    [long]$nowSeconds = [long]([DatetimeOffset]::Now).ToUnixTimeSeconds()
    [long]$expiresOn = [long]$InputObject.expires_on

    [int](($expiresOn - $nowSeconds) / 60)
}


<#
    .SYNOPSIS
        Invoke a password authorization flow specialized for the Azure Resource Management REST API
         
    .DESCRIPTION
        Invoke an OAuth 2.0 Password Grant flow that is specialized for the Azure Resource Management REST API
         
    .PARAMETER TenantName
        Name of the Azure AD tenant that you want the authrization request to work against
         
    .PARAMETER Username
        Username for the user that you want to authenticate as
         
    .PARAMETER Password
        Password for the user that you want to authenticate as
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Invoke-AzureResourceManagementGrant -TenantName "Contoso.onmicrosoft.com"
         
        This will authenticate against the "Contoso.onmicrosoft.com" tenant and get a valid OAuth token.
        It will prompt you for username and password which it will use for the authentication request.
         
    .EXAMPLE
        PS C:\> Invoke-AzureResourceManagementGrant -TenantName "Contoso.onmicrosoft.com" -Username "Alice" -Password "Pass@word1"
         
        This will authenticate against the "Contoso.onmicrosoft.com" tenant and get a valid OAuth token.
        It will use the provided username and password for the authentication request.
         
    .EXAMPLE
        PS C:\> Invoke-AzureResourceManagementGrant -TenantName "Contoso.onmicrosoft.com" -Username "Alice" -Password "Pass@word1" | Get-BearerToken
         
        This will provide you with a well formatted BearerToken string.
        This will authenticate against the "Contoso.onmicrosoft.com" tenant and get a valid OAuth token.
        It will use the provided username and password for the authentication request.
        It will pipe the output from Invoke-AzureResourceManagementGrant into the Get-BearerToken cmdlet.
         
    .NOTES
        Tags: ARM, Azure Resource Management, REST API
         
        Author: Mötz Jensen (@Splaxi)
#>


function Invoke-AzureResourceManagementGrant {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $TenantName,

        [string] $Username,

        [string] $Password,

        [switch] $EnableException
    )

    # Username and Password
    if ([String]::IsNullOrEmpty($Password)) {
        $credentials = Get-Credential -Message "Enter your credentials." -UserName $Username
    }
    else {
        $passwordSecured = ConvertTo-SecureString -String $Password -AsPlainText -Force
        $credentials = New-Object System.Management.Automation.PSCredential $Username, $passwordSecured
    }

    # Endpoint Uri used for authentication
    $authProviderUri = "https://login.microsoftonline.com/$TenantName/oauth2/token"

    $parms = @{ }
    $parms.AuthProviderUri = $authProviderUri
    $parms.Resource = "https://management.azure.com"
    $parms.ClientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $parms.GrantType = "password"
    $parms.Username = $credentials.GetNetworkCredential().username
    $parms.Password = $credentials.GetNetworkCredential().password
    $parms.Scope = "openid"

    Invoke-Authorization @parms
}


<#
    .SYNOPSIS
        Invoke a Client Credentials authorization flow
         
    .DESCRIPTION
        Invoke an OAuth 2.0 Client Credentials Grant flow against the authorization server
         
    .PARAMETER AuthProviderUri
        The URL / URI for the authorization server
         
    .PARAMETER Resource
        The URL / URI for the protected resource you want the token to be valid to
         
    .PARAMETER ClientId
        The Client Id that you want to use for the authentication process
         
    .PARAMETER ClientSecret
        The Client Secret that you want to use for the authentication process
         
    .PARAMETER TenantId
        The tenant id for the organization that you want to work agains
         
        It can be the full guid id OR it can be the current primary domain name
         
    .PARAMETER Scope
        The scope details that you want the token to valid for
         
    .PARAMETER AuthEndpointV1
        Instruct the cmdlet to work agains the v1 endpoint in Azure AD
         
    .PARAMETER AuthEndpointV2
        Instruct the cmdlet to work agains the v2 endpoint in Azure AD
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Invoke-ClientCredentialsGrant -AuthProviderUri "https://login.microsoftonline.com/e674da86-7ee5-40a7-b777-1111111111111/oauth2/token" -Resource "https://www.superfantasticservername.com" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -ClientSecret "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522="
         
        This will invoke an OAuth Client Credentials Grant flow against Azure Active Directory for the tenant id "e674da86-7ee5-40a7-b777-1111111111111".
        The token will be valid for the "https://www.superfantasticservername.com" resource.
        The ClientId is "dea8d7a9-1602-4429-b138-111111111111".
        The ClientSecret is "Vja/VmdxaLOPR+alkjfsadffelkjlfw234522="
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>


function Invoke-ClientCredentialsGrant {
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [OutputType()]
    param (
        [Parameter(ParameterSetName = "Default", Mandatory = $true)]
        [string] $AuthProviderUri,

        [Parameter(ParameterSetName = "Default", Mandatory = $true)]
        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [Parameter(ParameterSetName = "v2", Mandatory = $false)]
        [Alias('Url')]
        [Alias('Uri')]
        [string] $Resource,

        [Parameter(Mandatory = $true)]
        [string] $ClientId,

        [Parameter(Mandatory = $true)]
        [string] $ClientSecret,

        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [Alias('Tenant')]
        [string] $TenantId,

        [Parameter(ParameterSetName = "Default", Mandatory = $false)]
        [Parameter(ParameterSetName = "v1", Mandatory = $false)]
        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [string] $Scope,

        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [switch] $AuthEndpointV1,

        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [switch] $AuthEndpointV2,

        [switch] $EnableException
    )

    $parms = Get-DeepClone -InputObject $PSBoundParameters
    $parms.Remove("AuthEndpointV1") > $null
    $parms.Remove("AuthEndpointV2") > $null
    $parms.Remove("TenantId") > $null

    if (-not $AuthProviderUri) {
        $AuthProviderUri = if ($AuthEndpointV1) { "https://login.microsoftonline.com/{0}/oauth2/token" -f $TenantId } else { "https://login.microsoftonline.com/{0}/oauth2/v2.0/token" -f $TenantId }
    }

    $parms.AuthProviderUri = $AuthProviderUri
    
    Invoke-Authorization @parms -GrantType "client_credentials"
}


<#
    .SYNOPSIS
        Invoke a password authorization flow
         
    .DESCRIPTION
        Invoke an OAuth 2.0 Password Grant flow against the authorization server
         
    .PARAMETER AuthProviderUri
        The URL / URI for the authorization server
         
    .PARAMETER Resource
        The URL / URI for the protected resource you want the token to be valid to
         
    .PARAMETER ClientId
        The Client Id that you want to use for the authentication process
         
    .PARAMETER Username
        Username for the user that you want to authenticate as
         
    .PARAMETER Password
        Password for the user that you want to authenticate as
         
    .PARAMETER TenantId
        The tenant id for the organization that you want to work agains
         
        It can be the full guid id OR it can be the current primary domain name
         
    .PARAMETER Scope
        The scope details that you want the token to valid for
         
    .PARAMETER AuthEndpointV1
        Instruct the cmdlet to work agains the v1 endpoint in Azure AD
         
    .PARAMETER AuthEndpointV2
        Instruct the cmdlet to work agains the v2 endpoint in Azure AD
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Invoke-PasswordGrant -AuthProviderUri "https://login.microsoftonline.com/common/oauth2/token" -Resource "https://www.superfantasticservername.com" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -Username "serviceaccount@domain.com" -Password "TopSecretPassword" -Scope "openid"
         
        This will invoke an OAuth Password Grant flow against Azure Active Directory for the common endpoint.
        The token will be valid for the "https://www.superfantasticservername.com" resource.
        The ClientId is "dea8d7a9-1602-4429-b138-111111111111".
        The Username is "serviceaccount@domain.com".
        The Password is "TopSecretPassword".
        The Scope is "openid".
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>


function Invoke-PasswordGrant {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "")]
    [CmdletBinding(DefaultParameterSetName = "Default")]
    [OutputType()]
    param (
        [Parameter(ParameterSetName = "Default", Mandatory = $true)]
        [string] $AuthProviderUri,

        [Parameter(ParameterSetName = "Default", Mandatory = $true)]
        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [Parameter(ParameterSetName = "v2", Mandatory = $false)]
        [Alias('Url')]
        [Alias('Uri')]
        [string] $Resource,

        [Parameter(Mandatory = $true)]
        [string] $ClientId,

        [Parameter(Mandatory = $true)]
        [string] $Username,

        [Parameter(Mandatory = $true)]
        [string] $Password,

        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [Alias('Tenant')]
        [string] $TenantId,

        [Parameter(ParameterSetName = "Default", Mandatory = $false)]
        [Parameter(ParameterSetName = "v1", Mandatory = $false)]
        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [string] $Scope,

        [Parameter(ParameterSetName = "v1", Mandatory = $true)]
        [switch] $AuthEndpointV1,

        [Parameter(ParameterSetName = "v2", Mandatory = $true)]
        [switch] $AuthEndpointV2,

        [switch] $EnableException
    )

    $parms = Get-DeepClone -InputObject $PSBoundParameters
    $parms.Remove("AuthEndpointV1") > $null
    $parms.Remove("AuthEndpointV2") > $null
    $parms.Remove("TenantId") > $null

    if (-not $AuthProviderUri) {
        $AuthProviderUri = if ($AuthEndpointV1) { "https://login.microsoftonline.com/{0}/oauth2/token" -f $TenantId } else { "https://login.microsoftonline.com/{0}/oauth2/v2.0/token" -f $TenantId }
    }

    $parms.AuthProviderUri = $AuthProviderUri

    Invoke-Authorization @PSBoundParameters -GrantType "password"
}


<#
    .SYNOPSIS
        Invoke a refresh token authorization flow
         
    .DESCRIPTION
        Invoke an OAuth 2.0 Refresh Token Grant flow against the authorization server
         
    .PARAMETER AuthProviderUri
        The URL / URI for the authorization server
         
    .PARAMETER ClientId
        The Client Id that you want to use for the authentication process
         
    .PARAMETER RefreshToken
        The Refresh Token that you want to use for the authentication process
         
    .PARAMETER InputObject
        The object you received from any of the Invoke-* commands that returns an access token
         
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions
        This is less user friendly, but allows catching exceptions in calling scripts
         
    .EXAMPLE
        PS C:\> Invoke-RefreshToken -AuthProviderUri "https://login.microsoftonline.com/common/oauth2/token" -ClientId "dea8d7a9-1602-4429-b138-111111111111" -RefreshToken "Tsdljfasfe2j32324"
         
        This will invoke an Refresh Token Grant flow against Azure Active Directory for the common endpoint.
        The ClientId is "dea8d7a9-1602-4429-b138-111111111111".
        The RefreshToken is "Tsdljfasfe2j32324".
         
    .LINK
        Invoke-PasswordGrant
         
    .NOTES
         
        Tags: Refresh, Token, ClientId
         
        Author: Mötz Jensen (@Splaxi)
         
#>


function Invoke-RefreshToken {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "")]
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "Simple", Position = 1)]
        [Parameter(Mandatory = $true, ParameterSetName = "Object", Position = 1)]
        [string] $AuthProviderUri,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "Simple", Position = 2)]
        [Parameter(Mandatory = $true, ParameterSetName = "Object", Position = 2)]
        [string] $ClientId,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "Simple", Position = 3)]
        [Alias('refresh_token')]
        [Alias('Token')]
        [string] $RefreshToken,

        [Parameter(Mandatory = $false, ParameterSetName = "Object", Position = 3)]
        [PSCustomObject] $InputObject,

        [switch] $EnableException
    )

    process {
        if ($PsCmdlet.ParameterSetName -eq "Simple") {
            Invoke-Authorization @PSBoundParameters -GrantType "refresh_token"
        }
        else {
            Invoke-Authorization -AuthProviderUri $AuthProviderUri -ClientId $ClientId -GrantType "refresh_token" -RefreshToken $InputObject.refresh_token
        }
    }
}


<#
    .SYNOPSIS
        Get an authorization header
         
    .DESCRIPTION
        Get a valid HTTP header with the needed authorization details filled out for a bearer token
         
    .PARAMETER URL
        URI / URL for the endpoint that you want the header to be valid for
         
    .PARAMETER BearerToken
        The token value received from your earlier OAuth 2.0 flow
         
    .EXAMPLE
        PS C:\> New-AuthorizationHeaderBearerToken -URL "https://www.superfantasticservername.com" -BearerToken "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....."
         
        This will return a hashtable with the Authorization and Host elements filled out.
         
    .NOTES
        Tags: Header, Token, Bearer, Authorization
         
        Author: Mötz Jensen (@Splaxi)
         
#>


function New-AuthorizationHeaderBearerToken {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    [OutputType('System.Collections.Hashtable')]
    param (
        [Parameter(Mandatory = $true, Position = 1)]
        [Alias('URI')]
        [string] $URL,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 2)]
        [Alias('access_token')]
        [string] $BearerToken
    )

    process {
        if (-not ($BearerToken.StartsWith("Bearer "))) {
            $BearerToken = "Bearer $BearerToken"
        }

        @{
            "Authorization" = "$BearerToken"
            "Host"          = ([uri]$URL).Host
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'PSOAuthHelper' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'PSOAuthHelper' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'PSOAuthHelper' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'PSOAuthHelper.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "PSOAuthHelper.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name PSOAuthHelper.alcohol
#>


New-PSFLicense -Product 'PSOAuthHelper' -Manufacturer 'Motz' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-02-28") -Text @"
Copyright (c) 2019 Motz
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code