functions/Get-AadDiscoveryKeys.ps1


function Get-AadDiscoveryKeys
{
    [CmdletBinding(DefaultParameterSetName='Default')]
    param(
        [Parameter(ParameterSetName = 'SetTenantAndInstance')]
        [string]$Tenant, 

        [Parameter(ParameterSetName = 'SetTenantAndInstance')]
        [string]$AadInstance,

        [Parameter(ParameterSetName = 'SetIssuer')]
        [string]$Issuer,

        [string]$ApplicationId
    ) 

    if ($Issuer -match ".well-known/openid-configuration")
    {
        $Issuer = $Issuer.Replace("/.well-known/openid-configuration", "")
    }

    # Populate Tenant info
    if($Global:AadSupport.Session -and -not $Tenant)
    {
        $Tenant = $Global:AadSupport.Session.TenantId

        if(-not $Tenant)
        {
            $Tenant = "common"
        }
    }

    # Populate AadInstance info
    if($Global:AadSupport.Session -and -not $AadInstance)
    {
        $Tenant = $Global:AadSupport.Session.AadInstance

        if(-not $AadInstance)
        {
            $AadInstance = "https://login.microsoftonline.com"
        }
    }


    # Set the Discovery Key Endpoint
    if(!$Issuer)
    {
        $Issuer = "$AadInstance/$Tenant"
    }

    $KeyUrl = "$Issuer/discovery/keys"

    if($ApplicationId)
    {
        $KeyUrl += "?appid=$ApplicationId"
    }

    # Get the Discovery Keys
    $Keys = (ConvertFrom-Json (Invoke-WebRequest $KeyUrl -Verbose).Content).Keys
    
    # Build the Output object
    $ReturnObject = @()

    foreach($Key in $Keys)
    {
        $Object = [pscustomobject]@{} 

        $Object | Add-Member -NotePropertyName Kid -NotePropertyValue $Key.kid
        $Object | Add-Member -NotePropertyName Use -NotePropertyValue $Key.use
        $Object | Add-Member -NotePropertyName x5t -NotePropertyValue $Key.x5t
        $Object | Add-Member -NotePropertyName kty -NotePropertyValue $Key.kty
        $Object | Add-Member -NotePropertyName Modulus -NotePropertyValue $Key.n
        $Object | Add-Member -NotePropertyName Exponent -NotePropertyValue $Key.e

        if($Key.x5c)
        {
            $Certificate = ConvertFrom-AadBase64Certificate -Base64String $Key.x5c[0]
            $Thumbprint = $Certificate.Thumbprint

            $Object | Add-Member -NotePropertyName Certificate -NotePropertyValue $Certificate
            $Object | Add-Member -NotePropertyName Thumbprint -NotePropertyValue $Thumbprint
            $Object | Add-Member -NotePropertyName x5c -NotePropertyValue $Key.x5c[0]
        }

        $ReturnObject += $Object
    }

    return $ReturnObject
}