Functions/Test-GraphSecurityAuthToken.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
50
51
52
53
54
55
56
57
58
59
60
<#
.Synopsis
   Internal function to test if the current sessions has a Authentication Token for Microsoft Graph Security.
 
.DESCRIPTION
   Tests if the current sessions has a Authentication Token for Microsoft Graph Security.
 
.EXAMPLE
   Test-GraphSecurityAuthToken
 
.FUNCTIONALITY
   Test-GraphSecurityAuthToken is intended as an internal function to test for Authentication Token.
#>


function Test-GraphSecurityAuthToken {

    # Checking if authToken exists before running authentication
    if ($global:GraphSecurityauthHeader) {

        # Setting DateTime to Universal time to work in all timezones
        $DateTime = (Get-Date).ToUniversalTime()

        # If the authToken exists checking when it expires
        $TokenExpires = ($GraphSecurityauthHeader.ExpiresOn.datetime - $DateTime).Minutes

        if ($TokenExpires -le 0) {

            #Token is expired, check for UserName and AppId, and go get a token
            Write-Warning "Authentication Token expired $TokenExpires minutes ago"

            Try { $Username = Select-GraphSecurityUsername }
            Catch { Throw $_ }

            Try { $AppId = Select-GraphSecurityAppId }
            Catch { Throw $_ }

            Write-Warning "Refreshing Auth Token"
            Get-GraphSecurityAuthToken

        }
    }


    # Authentication doesn't exist, calling Get-GraphSecurityAuthToken function

    else {

        Try { $Username = Select-GraphSecurityUsername }
        Catch { Throw $_ }

        Try { $AppId = Select-GraphSecurityAppId }
        Catch { Throw $_ }

        Get-GraphSecurityAuthToken

    }


}