AzureADAuthMethods.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\AzureADAuthMethods.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = $false
if ($AzureADAuthMethods_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 = $false
if ($AzureADAuthMethods_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path "$($script:ModuleRoot)\..\.git") { $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
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # 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
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
function Assert-GraphConnection
{
<#
    .SYNOPSIS
        Asserts a valid graph connection has been established.
     
    .DESCRIPTION
        Asserts a valid graph connection has been established.
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling command.
     
    .EXAMPLE
        PS C:\> Assert-GraphConnection -Cmdlet $PSCmdlet
     
        Asserts a valid graph connection has been established.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    
    process
    {
        if ($script:msgraphToken) { return }
        
        $exception = [System.InvalidOperationException]::new('Not yet connected to MSGraph. Use Connect-AzureADUserAuthenticationMethod to establish a connection!')
        $errorRecord = [System.Management.Automation.ErrorRecord]::new($exception, "NotConnected", 'InvalidOperation', $null)
        
        $Cmdlet.ThrowTerminatingError($errorRecord)
    }
}

function ConvertTo-AuthHeader {
<#
    .SYNOPSIS
        Generates an authentication header from a graph token.
     
    .DESCRIPTION
        Generates an authentication header from a graph token.
     
    .PARAMETER Token
        The token from which to build the authentication header.
     
    .EXAMPLE
        PS C:\> Get-Token | ConvertTo-AuthHeader
     
        Generates an authentication header from a graph token.
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $Token
    )
    
    process {
        foreach ($tokenObject in $Token) {
            @{
                Authorization = "Bearer $($tokenObject.AccessToken)"
                'Content-Type' = 'application/json'
                'Accept'      = 'application/json, text/plain'
            }
        }
    }
}

function Get-Token
{
<#
    .SYNOPSIS
        Returns the token to use for authentication to MSGraph.
     
    .DESCRIPTION
        Returns the token to use for authentication to MSGraph.
        Automatically refreshes it if it is close to expiration.
     
    .EXAMPLE
        PS C:\> Get-Token
     
        Returns the token to use for authentication to MSGraph.
#>

    [CmdletBinding()]
    Param (
    
    )
    
    process
    {
        if ($script:msgraphToken -and $script:msgraphToken.ExpiresOn.LocalDateTime -gt (Get-Date).AddMinutes(3)) {
            return $script:msgraphToken
        }
        
        $parameters = @{
            TenantId = $script:tenantID
            ClientId = $script:clientID
            ErrorAction = 'Stop'
        }
        if ($script:clientCertificate) {
            $parameters.ClientCertificate = $script:clientCertificate
        }
        else {
            $parameters.RedirectUri = $script:redirectUri
            $parameters.LoginHint = $script:msgraphToken.Account.Username
            $parameters.Silent = $true
        }
        
        try { $token = Get-MsalToken @parameters }
        catch {
            Write-Warning "Failed to re-authenticate to tenant $script:tenantID : $_"
            throw
        }
        $script:msgraphToken = $token
        return $token
    }
}

function Invoke-AzureAdRequest
{
<#
    .SYNOPSIS
        Execute an arbitrary graph call against AzureAD endpoints.
     
    .DESCRIPTION
        Execute an arbitrary graph call against AzureAD endpoints.
        Handles authentication & token refresh transparently.
     
    .PARAMETER Query
        The actual query to execute.
     
    .PARAMETER Method
        The REST method to apply
     
    .PARAMETER Body
        Any body data to pass along as part of the request
     
    .PARAMETER GetValues
        Get the content of the .Value property, rather than the raw response content
     
    .PARAMETER Raw
        Get raw response
     
    .EXAMPLE
        PS C:\> Invoke-AzureAdRequest -Query 'users/3ec9f2ec-aeec-4ad9-ad18-b456288fdb32/authentication/phonemethods' -Method GET
         
        Retrieve the phone authentication settings for the specified user.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Query,
        
        [Parameter(Mandatory = $true)]
        [string]
        $Method,
        
        $Body,
        
        [switch]
        $GetValues,
        
        [switch]
        $Raw
    )
    
    begin
    {
        try { $authHeader = Get-Token | ConvertTo-AuthHeader }
        catch { throw }
        
        $parameters = @{
            Method = $Method
            Uri    = "$($script:baseUri.Trim("/"))/$($Query.TrimStart("/"))"
            Headers = $authHeader
        }
        if ($Body) { $parameters.Body = $Body }
    }
    process
    {
        try { $response = Invoke-RestMethod @parameters -ErrorAction Stop }
        catch { throw }
        
        
        if ($Raw) { return $response }
        if ($GetValues) { return $response.Value }
        $response.Value
        
    }
}


function Connect-AzureADUserAuthenticationMethod {
    [CmdletBinding(DefaultParameterSetName = 'Interactive')]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $TenantId,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $Certificate,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
        [string]
        $Thumbprint,
        
        [Parameter(ParameterSetName = 'Thumbprint')]
        [string]
        $CertificateStore = 'Cert:\CurrentUser\My',
        
        [Parameter(ParameterSetName = 'Interactive')]
        [switch]
        $Interactive,
        
        [string]
        $ClientID = "",
        
        [string]
        $RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
        
        [string]
        $BaseUri = 'https://graph.microsoft.com/beta/',
        
        [switch]
        $PassThru
    )
    
    process {
        if ($Thumbprint) {
            try { $Certificate = Get-Item -Path (Join-Path -Path $CertificateStore -ChildPath $Thumbprint) }
            catch { throw "Unable to find certificate $Thumbprint in certificate store $CertificateStore !" }
        }
        switch ($PSCmdlet.ParameterSetName) {
            'Interactive' {
                try { $token = Get-MsalToken -TenantId $TenantId -ClientId $ClientID -RedirectUri $RedirectUri -Interactive }
                catch {
                    Write-Warning "Failed to authenticate to tenant $TenantID : $_"
                    throw
                }
            }
            default {
                try { $token = Get-MsalToken -TenantId $TenantId -ClientId $ClientID -ClientCertificate $Certificate }
                catch {
                    Write-Warning "Failed to authenticate to tenant $TenantID : $_"
                    throw
                }
            }
        }
        
        $script:msgraphToken = $token
        $script:baseUri = $BaseUri
        $script:tenantID = $TenantId
        $script:clientID = $ClientID
        $script:redirectUri = $RedirectUri
        $script:clientCertificate = $Certificate
        
        if ($PassThru) { $token }
    }
}


function Get-AzureADUserAuthenticationMethod {
    <#
    .SYNOPSIS
        Gets a user's authentication methods.
    .DESCRIPTION
        Gets a user's authentication methods.
        All methods are returned by default. Pass the required method as a switch to only get that method.
    .EXAMPLE
        PS C:\>Get-AzureADUserAuthenticationMethod -ObjectId user@contoso.com -Phone
        Gets the phone authentication methods set for the user.
    .EXAMPLE
        PS C:\>Get-AzureADUser -SearchString user1@contoso.com | Get-AzureADUserAuthenticationMethod
        Gets the phone authentication methods set for the user from the pipeline.
    .EXAMPLE
        PS C:\>Get-AzureADUserAuthenticationMethod -UserPrincipalName user@contoso.com -Phone
        Gets the phone authentication methods set for the user.
    #>

    [CmdletBinding(DefaultParameterSetName = 'allMethods')]
    param (
        [Parameter(Mandatory = $True, ParameterSetName = 'pin')]
        [switch]
        $Pin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'softwareOath')]
        [switch]
        $softwareOath,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [switch]
        $Phone,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'email')]
        [switch]
        $Email,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'password')]
        [switch]
        $Password,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [switch]
        $SecurityQuestion,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'FIDO2')]
        [switch]
        $FIDO2,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'passwordlessMicrosoftAuthenticator')]
        [switch]
        $PasswordlessMicrosoftAuthenticator,

        [Parameter(Mandatory = $True, ParameterSetName = 'MicrosoftAuthenticator')]
        [switch]
        $MicrosoftAuthenticator,

        [Parameter(Mandatory = $True, ParameterSetName = 'WindowsHelloForBusiness')]
        [switch]
        $WindowsHelloForBusiness,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'default')]
        [switch]
        $Default,
        
        [Alias('UserId', 'UPN', 'UserPrincipalName')]
        [Parameter(Mandatory = $True, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ObjectId
    )
    begin {
        Assert-GraphConnection -Cmdlet $PSCmdlet

        $common = @{
            Method = 'GET'
            GetValues = $false
        }
    }
    process {
        $values = switch ($PSCmdlet.ParameterSetName) {
            "phone" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/phoneMethods"
                break
            }
            "email" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/emailMethods"
                break
            }
            "password" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/passwordMethods"
                break
            }
            "FIDO2" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/fido2Methods"
                break
            }
            "passwordlessMicrosoftAuthenticator" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/passwordlessMicrosoftAuthenticatorMethods"
                break
            }
            "MicrosoftAuthenticator" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/MicrosoftAuthenticatorMethods"
                break
            }
            "WindowsHelloForBusiness" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/windowsHelloForBusinessMethods"
                break
            }
            "allMethods" {
                Invoke-AzureAdRequest @common -Query "users/$ObjectId/authentication/methods"
                break
            }
            default {
                throw "Getting the $($PSCmdlet.ParameterSetName) method is not yet supported."
            }
        }
        $values  | Add-Member -NotePropertyName userObjectId -NotePropertyValue $ObjectId -PassThru
    }
}


function New-AzureADUserAuthenticationMethod {
    <#
    .SYNOPSIS
        Creates a new authentication method for the user.
    .DESCRIPTION
        Creates a new authentication method for the user.
        Use to create a new method type for the user. To modify a method, use Update-AzureADUserAuthenticationMethod.
    .EXAMPLE
        PS C:\>New-AzureADUserAuthenticationMethod user@contoso.com -Phone -PhoneNumber '+61412345678' -PhoneType mobile
        Adds a new mobile phone authentication method to the user.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True, ParameterSetName = 'pin')]
        [switch]
        $Pin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [switch]
        $Oath,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'password')]
        [switch]
        $Password,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [switch]
        $SecurityQuestion,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'default')]
        [switch]
        $Default,
        
        [Alias('UserId', 'UPN', 'UserPrincipalName')]
        [Parameter(Mandatory = $True, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ObjectId,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'pin', Position = 2)]
        [string]
        $NewPin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $SecretKey,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [int]
        $TimeIntervalInSeconds,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $SerialNumber,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $Manufacturer,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $Model,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [string]
        $PhoneNumber,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [ValidateSet("mobile", "alternateMobile", "office")]
        [string]
        $PhoneType,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'email', Position = 2)]
        [string]
        $EmailAddress,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'password')]
        [string]
        $NewPassword,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [string]
        $Question,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [string]
        $Answer
        
    )
    
    begin {
        Assert-GraphConnection -Cmdlet $PSCmdlet
    }
    process {
        switch ($PSCmdlet.ParameterSetName) {
            "phone" {
                $postParams = @{
                    phoneNumber = $PhoneNumber
                    phoneType = $PhoneType
                }
                $json = $postparams | ConvertTo-Json -Depth 99 -Compress
                Invoke-AzureAdRequest -Method POST -Query "users/$ObjectId/authentication/phoneMethods" -Body $json
                break
            }
            "email" {
                $postParams = @{
                    emailAddress = $EmailAddress
                }
                $json = $postparams | ConvertTo-Json -Depth 99 -Compress
                Invoke-AzureAdRequest -Method POST -Query "users/$ObjectId/authentication/emailMethods" -Body $json
                break
            }
            default {
                throw "Setting the $($PSCmdlet.ParameterSetName) method is not yet supported."
            }
        }
    }
}


function Remove-AzureADUserAuthenticationMethod {
    <#
    .SYNOPSIS
        Removes an authentication method from the user.
    .DESCRIPTION
        Removes an authentication method from the user.
        Use to remove an existing authentication method for the user.
    .EXAMPLE
        PS C:\>Remove-AzureADUserAuthenticationMethod -Phone -PhoneType mobile user@contoso.com
        Removes the mobile phone authentication method for the user.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True, ParameterSetName = 'pin')]
        [switch]
        $Pin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [switch]
        $Oath,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [switch]
        $Phone,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'email')]
        [switch]
        $Email,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'password')]
        [switch]
        $Password,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'FIDO2')]
        [switch]
        $FIDO2,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'passwordlessMicrosoftAuthenticator')]
        [switch]
        $PasswordlessMicrosoftAuthenticator,

        [Parameter(Mandatory = $True, ParameterSetName = 'MicrosoftAuthenticator')]
        [switch]
        $MicrosoftAuthenticator,

        [Parameter(Mandatory = $True, ParameterSetName = 'WindowsHelloForBusiness')]
        [switch]
        $WindowsHelloForBusiness,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'FIDO2')]
        [Parameter(Mandatory = $True, ParameterSetName = 'passwordlessMicrosoftAuthenticator')]
        [Parameter(Mandatory = $True, ParameterSetName = 'MicrosoftAuthenticator')]
        [Parameter(Mandatory = $True, ParameterSetName = 'WindowsHelloForBusiness')]
        [string]
        $MethodId,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [switch]
        $SecurityQuestion,
        
        [Alias('UserId', 'UPN', 'UserPrincipalName')]
        [Parameter(Mandatory = $True, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ObjectId,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $SerialNumber,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [ValidateSet("mobile", "alternateMobile", "office")]
        [string]
        $PhoneType,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [string]
        $Question
        
    )
    
    begin {
        Assert-GraphConnection -Cmdlet $PSCmdlet
    }
    process {
        switch ($PSCmdlet.ParameterSetName) {
            "phone" {
                $methodId = switch ($PhoneType) {
                    'alternateMobile' { 'b6332ec1-7057-4abe-9331-3d72feddfe41' }
                    'mobile' { '3179e48a-750b-4051-897c-87b9720928f7' }
                    'office' { 'e37fc753-ff3b-4958-9484-eaa9425c82bc' }
                }
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/phoneMethods/$methodId"
                break
            }
            "email" {
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/emailMethods/3ddfcfc8-9383-446f-83cc-3ab9be4be18f"
                break
            }
            "FIDO2" {
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/fido2Methods/$MethodId"
                break
            }
            "passwordlessMicrosoftAuthenticator" {
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/passwordlessMicrosoftAuthenticatorMethods/$MethodId"
                break
            }
            "MicrosoftAuthenticator" {
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/MicrosoftAuthenticatorMethods/$MethodId"
                break
            }
            "WindowsHelloForBusiness" {
                Invoke-AzureAdRequest -Method DELETE -Query "users/$ObjectId/authentication/windowsHelloForBusinessMethods/$MethodId"
                break
            }
            default {
                throw "Removing the $($PSCmdlet.ParameterSetName) method is not yet supported."
            }
        }
    }
}


function Update-AzureADUserAuthenticationMethod {
    <#
.SYNOPSIS
    Modifies an authentication method for the user. Manages SMS Sign In for mobile phone method.
.DESCRIPTION
    Modifies an authentication method for the user. Manages SMS Sign In for mobile phone method.
    Use to modify an existing authentication method for the user. To create a new method, use New-AzureADUserAuthenticationMethod.
.EXAMPLE
    PS C:\>Update-AzureADUserAuthenticationMethod user@contoso.com -Phone -PhoneNumber '+61412345679' -PhoneType mobile
    Modifies the existing mobile phone number for the user.
.EXAMPLE
    PS C:\>Update-AzureADUserAuthenticationMethod -Phone -UPN user1@contoso.com -EnableSmsSignIn
    Enables SMS sign-in for the existing mobile phone authentication method for the user.
.EXAMPLE
    PS C:\>Update-AzureADUserAuthenticationMethod user@contoso.com -Password -NewPassword "password"
    Sets "password" as a new password for the user. Doesn't return the operation result.
.EXAMPLE
    PS C:\>Update-AzureADUserAuthenticationMethod user@contoso.com -Password -NewPassword "password" -ReturnResult
    Sets "password" as a new password for the user and waits 5 seconds for the operation result.
.EXAMPLE
    PS C:\>Update-AzureADUserAuthenticationMethod clouduser@contoso.com -Password
    Sets new system generated password for the user. Not available for syncronised users.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True, ParameterSetName = 'pin')]
        [switch]
        $Pin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [switch]
        $Oath,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'password')]
        [switch]
        $Password,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [switch]
        $SecurityQuestion,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'default')]
        [switch]
        $Default,
        
        [Alias('UserId', 'UPN', 'UserPrincipalName')]
        [Parameter(Mandatory = $True, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $ObjectId,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'pin', Position = 2)]
        [string]
        $NewPin,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $SecretKey,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [int]
        $TimeIntervalInSeconds,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $SerialNumber,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $Manufacturer,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'oath')]
        [string]
        $Model,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [string]
        $PhoneNumber,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'phone')]
        [ValidateSet("mobile", "alternateMobile", "office")]
        [string]
        $PhoneType,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'email', Position = 2)]
        [string]
        $EmailAddress,
        
        [Parameter(Mandatory = $False, ParameterSetName = 'password')]
        [string]
        $NewPassword,
        
        [Parameter(Mandatory = $False, ParameterSetName = 'password')]
        [switch]
        $ReturnResult,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [string]
        $Question,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'securityQuestion')]
        [string]
        $Answer,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'default')]
        [string]
        $DefaultMethod,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'enableSmsSignIn')]
        [switch]
        $EnableSmsSignIn,
        
        [Parameter(Mandatory = $True, ParameterSetName = 'disableSmsSignIn')]
        [switch]
        $DisableSmsSignIn
    )
    
    begin {
        Assert-GraphConnection -Cmdlet $PSCmdlet
    }
    process {
        switch ($PSCmdlet.ParameterSetName) {
            "phone" {
                $methodId = switch ($PhoneType) {
                    'alternateMobile' { 'b6332ec1-7057-4abe-9331-3d72feddfe41' }
                    'mobile' { '3179e48a-750b-4051-897c-87b9720928f7' }
                    'office' { 'e37fc753-ff3b-4958-9484-eaa9425c82bc' }
                }
                
                $postParams = @{
                    phoneNumber = $PhoneNumber
                    phoneType   = $PhoneType
                }
                $json = $postparams | ConvertTo-Json -Depth 99 -Compress
                Invoke-AzureAdRequest -Method PUT -Query "users/$ObjectId/authentication/phoneMethods/$methodId" -Body $json
                break
            }
            "email" {
                $postParams = @{
                    emailAddress = $EmailAddress
                }
                $json = $postparams | ConvertTo-Json -Depth 99 -Compress
                Invoke-AzureAdRequest -Method PUT -Query "users/$ObjectId/authentication/emailMethods/3ddfcfc8-9383-446f-83cc-3ab9be4be18f" -Body $json
                break
            }
            "password" {
                $parameters = @{
                    Method = 'POST'
                    Query = "users/$ObjectId/authentication/passwordMethods/28c10230-6103-485e-b985-444c60001490/resetPassword"
                }
                if ($NewPassword) {
                    $parameters.Body = @{
                        newPassword = $NewPassword
                    } | ConvertTo-Json -Depth 99 -Compress
                }
                $response = Invoke-AzureAdRequest @parameters -Raw
                if (-not $ReturnResult) { return $response }
                
                # TODO: If RAW, use invoke-webrequest to get response headers.
                # Check password reset result
                if ($response.StatusCode -eq "202") {
                    Write-Host "Waiting for a response..."
                    Start-Sleep -Seconds 5
                    (Invoke-WebRequest -UseBasicParsing -Headers (Get-Token | ConvertTo-AuthHeader) -Uri $response.Headers.Location -Method Get).Content
                }
                
                return $response.Content
            }
            "enableSmsSignIn" {
                Invoke-AzureAdRequest -Method PUT -Query "users/$ObjectId/authentication/phoneMethods/3179e48a-750b-4051-897c-87b9720928f7/enableSmsSignIn" -Body $json
                break
            }
            "disableSmsSignIn" {
                Invoke-AzureAdRequest -Method PUT -Query "users/$ObjectId/authentication/phoneMethods/3179e48a-750b-4051-897c-87b9720928f7/disableSmsSignIn" -Body $json
                break
            }
            default {
                throw "Setting the $($PSCmdlet.ParameterSetName) method is not yet supported."
            }
        }
    }
}


# Graph Token to use for queries
$script:msgraphToken = $null

# The API base URI to use for requests
$script:baseUri = 'https://graph.microsoft.com/beta/'

# Certificate used for authenticating inapplication authentication workflows
$script:clientCertificate = $null

# Connection Metadata
$script:tenantID = ''
$script:clientID = ''
$script:redirectUri = 'urn:ietf:wg:oauth:2.0:oob'
#endregion Load compiled code