Public/Get-AllegisIDNOAuthAccessToken.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-AllegisIDNOAuthAccessToken {
Param(
    [Parameter(Mandatory=$true, ParameterSetName="client_credentials")]
    [Parameter(Mandatory=$true, ParameterSetName="password")]
    [Parameter(Mandatory=$true, ParameterSetName="refresh_token")]
    [string]$org,
    [Parameter(Mandatory=$true, ParameterSetName="client_credentials")]
    [Parameter(Mandatory=$true, ParameterSetName="password")]
    [Parameter(Mandatory=$true, ParameterSetName="refresh_token")]
    [string]$clientid,
    [Parameter(Mandatory=$true, ParameterSetName="client_credentials")]
    [Parameter(Mandatory=$true, ParameterSetName="password")]
    [Parameter(Mandatory=$true, ParameterSetName="refresh_token")]
    [string]$clientsecret,    
    [Parameter(Mandatory=$true, ParameterSetName="password")]
    [string]$adminusername,
    [Parameter(Mandatory=$true, ParameterSetName="password")]
    [string]$adminpassword,
    [Parameter(Mandatory=$true, ParameterSetName="refresh_token")]
    [string]$refreshtoken
)
    if ($clientID.length -ne 36){Write-Warning "unexpected size for client ID, proceeding"}
    $url="https://$org.api.identitynow.com/oauth/token"
    $Bytes = [System.Text.Encoding]::utf8.GetBytes("$($clientID):$($clientSecret)")
    $encodedAuth = [Convert]::ToBase64String($Bytes)
    $Header = @{Authorization = "Basic $($encodedAuth)"}
    switch ($PsCmdlet.ParameterSetName){
        client_credentials{
            Write-Warning "grant type client_credentials will not always have access to admin functions, you may get 403 depending on what api you use"
            $Token = Invoke-RestMethod -Method Post -Uri "$($url)?grant_type=client_credentials" -Headers $Header
        }
        password{
            $adminusername = $adminusername.ToLower()
            $passwordHash = Get-Hash -Algorithm SHA256 -StringEncoding utf8 -InputObject ($($adminpassword) + (Get-Hash -Algorithm SHA256 -StringEncoding utf8 -InputObject ($adminusername)).HashString.ToLower())
            $adminPWD = $passwordHash.ToString().ToLower()
            $Token = Invoke-RestMethod -Method Post -Uri "$($url)?grant_type=password&username=$($adminusername)&password=$($adminPWD)" -Headers $Header
        }
        refresh_token{
            $Body = @{
            grant_type = $PsCmdlet.ParameterSetName
            client_id = $clientID
            client_secret = [System.Web.HttpUtility]::UrlEncode($clientSecret)
            refresh_token = $refreshtoken
            }
            $Token = Invoke-RestMethod -Method Post -Uri $url -Body $body -UseBasicParsing -ContentType 'application\json'
        }
    }
    return $token
}