· 7 years ago · Oct 26, 2018, 03:32 AM
1function Generate-JWT (
2 [Parameter(Mandatory = $True)]
3 [ValidateSet("HS256", "HS384", "HS512")]
4 $Algorithm = $null,
5 $type = $null,
6 [Parameter(Mandatory = $True)]
7 [string]$Issuer = $null,
8 [int]$ValidforSeconds = $null,
9 [Parameter(Mandatory = $True)]
10 $SecretKey = $null
11 ){
12
13 $exp = [int][double]::parse((Get-Date -Date $((Get-Date).addseconds($ValidforSeconds).ToUniversalTime()) -UFormat %s)) # Grab Unix Epoch Timestamp and add desired expiration.
14
15 [hashtable]$header = @{alg = $Algorithm; typ = $type}
16 [hashtable]$payload = @{iss = $Issuer; exp = $exp}
17
18 $headerjson = $header | ConvertTo-Json -Compress
19 $payloadjson = $payload | ConvertTo-Json -Compress
20
21 $headerjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($headerjson)).Split('=')[0].Replace('+', '-').Replace('/', '_')
22 $payloadjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($payloadjson)).Split('=')[0].Replace('+', '-').Replace('/', '_')
23
24 $ToBeSigned = $headerjsonbase64 + "." + $payloadjsonbase64
25
26 $SigningAlgorithm = switch ($Algorithm) {
27 "HS256" {New-Object System.Security.Cryptography.HMACSHA256}
28 "HS384" {New-Object System.Security.Cryptography.HMACSHA384}
29 "HS512" {New-Object System.Security.Cryptography.HMACSHA512}
30 }
31
32 $SigningAlgorithm.Key = [System.Text.Encoding]::UTF8.GetBytes($SecretKey)
33 $Signature = [Convert]::ToBase64String($SigningAlgorithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($ToBeSigned))).Split('=')[0].Replace('+', '-').Replace('/', '_')
34
35 $token = "$headerjsonbase64.$payloadjsonbase64.$Signature"
36 $token
37}
38
39$api_key = ''
40$api_secret = ''
41
42Generate-JWT -Algorithm 'HS256' -type 'JWT' -Issuer $api_key -SecretKey $api_secret -ValidforSeconds 30
43
44# Generate JWT for use in API calls.
45$token = Generate-JWT -Algorithm 'HS256' -type 'JWT' -Issuer $api_key -SecretKey $api_secret -ValidforSeconds 30
46
47# Generate Header for API calls.
48[string]$contentType = 'application/json'
49$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
50$headers.Add('Content-Type' , $contentType)
51$headers.Add('Authorization','Bearer ' + $token)
52
53# Pull all API device data.
54$query_result = Invoke-RestMethod -Uri "$base_uri/metrics/zoomrooms?page_size=300&page_number=$page_number" -Headers $headers -Method GET