internal/functions/Get-Token.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
    }
}