Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Required by the New-ClearpassUri function
- Add-Type -AssemblyName 'System.Web'
- <#
- * Clearpass API functions expect these variables to be defined and reference them from $script: scope
- #Connection config for Clearpass API
- $ClearpassConfig = @{'Hostname' = '10.121.9.9'
- 'HostScheme' = 'https'
- 'HostPort' = '443'}
- #Credentials for Clearpass API
- $ClearpassConfig.AuthBody = @{"grant_type" = "password"
- "username" = "api"
- "password" = "password"
- "client_id" = "customer"}
- #>
- $script:ClearpassTokenCache = @{'Token' = $null
- 'Expires' = $null}
- #region api functions clearpass
- function Get-ClearpassToken {
- <#
- .SYNOPSIS
- Return a Clearpass token, either from cache variable $script:ClearpassTokenCache where not expired, or fetch a new one
- .OUTPUTS
- String - bearer token
- #>
- if($null -eq $script:ClearpassTokenCache.Token -or $script:ClearpassTokenCache.expires -lt (Get-Date)){
- $Response = Invoke-ClearpassApi -Path @('oauth') -Body $global:ClearpassConfig.AuthBody -Method 'POST' -OAuth
- if($null -ne $Response.access_token){
- $script:ClearpassTokenCache.Token = $Response.access_token
- $script:ClearpassTokenCache.Expires = (Get-Date).AddSeconds($Response.expires_in - 60)
- } else {
- Throw "No access token in oauth response `"$Response`""
- }
- }
- return $script:ClearpassTokenCache.Token
- }
- function New-ClearpassUri {
- <#
- .SYNOPSIS
- Create the URI for a Clearpass API request
- .DESCRIPTION
- Internal function used to build a URIBuilder object.
- .PARAMETER Path
- Array of strings for each segment in the URL path
- .PARAMETER Query
- Hashtable of query parameters to include
- #>
- [CmdletBinding()]
- [OutputType([System.UriBuilder])]
- param
- (
- [Parameter(Mandatory = $false)]
- [string[]]$Path,
- [Parameter(Mandatory = $false)]
- [hashtable]$Query
- )
- Write-Debug "Building URI"
- # Begin a URI builder with HTTP/HTTPS and the provided hostname
- $UriBuilder = [System.UriBuilder]::new($global:ClearpassConfig.HostScheme, $global:ClearpassConfig.Hostname, $global:ClearpassConfig.HostPort)
- # Generate the path by trimming excess slashes and whitespace from the $Path[] and joining together
- $UriBuilder.Path = "api/{0}" -f ($Path.ForEach({
- $_.trim('/').trim()
- }) -join '/')
- Write-Debug " URIPath: $($UriBuilder.Path)"
- if ($Query) {
- # Loop through the parameters and use the HttpUtility to create a Query string
- [System.Collections.Specialized.NameValueCollection]$URIParams = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
- foreach ($param in $Query.GetEnumerator()) {
- Write-Debug " Adding URI parameter $($param.Key):$($param.Value)"
- $URIParams[$param.Key] = $param.Value
- }
- $UriBuilder.Query = $URIParams.ToString()
- }
- # Return the entire UriBuilder object
- $UriBuilder
- }
- function Invoke-ClearpassApi {
- <#
- .SYNOPSIS
- Execute a Clearpass API request
- .DESCRIPTION
- Invoke an HTTP request to the API and return results
- The Get-ClearpassChunkedResult function should be used for queries which may return multiple
- results, it will make multiple requests and combine results in the _embedded.items property
- of the API response if required (API does not return unlimited record counts)
- A set request or query which will only return 0 or 1 results can call this function directly
- as the JSON response is suitable for consumption
- .PARAMETER Path
- Array of strings for each segment in the URL path - passed to New-ApiUri
- .PARAMETER Query
- Hashtable of query parameters to include - passed to New-ApiUri
- .PARAMETER Headers
- Hashtable of HTTP Request headers
- .PARAMETER Body
- Object for HTTP Request body
- .PARAMETER Method
- HTTP Request method
- .PARAMETER OAuth
- Switch - if this is the oauth token request, obviously we won't have a token
- #>
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $false)]
- [string[]]$Path,
- [Parameter(Mandatory = $false)]
- [hashtable]$Query,
- [Hashtable]$Headers = @{},
- [pscustomobject]$Body = $null,
- [ValidateSet('GET', 'PATCH', 'PUT', 'POST', 'DELETE', 'OPTIONS', IgnoreCase = $true)]
- [string]$Method = 'GET',
- [switch]$OAuth
- )
- $Uri = New-ClearpassUri -Path $Path -Query $Query
- if(!$OAuth){
- $Headers.Authorization = "Bearer {0}" -f (Get-ClearpassToken)
- }
- #ClearPass API was picky about this
- $Headers.Accept = '*/*'
- $Splat = @{
- 'Method' = $Method
- 'Uri' = $URI.Uri.AbsoluteUri # This property auto generates the scheme, hostname, path, and query
- 'Headers' = $Headers
- 'TimeoutSec' = 180
- 'ContentType' = 'application/json'
- }
- #BasicParsing is required on Server Core, without it Invoke-RestMethod tries to run Internet Explorer
- $Splat += @{'UseBasicParsing' = $true}
- if ($Body) {
- Write-Debug "BODY: $($Body | ConvertTo-Json -Compress)"
- $null = $Splat.Add('Body', ($Body | ConvertTo-Json -Compress))
- }
- try {
- $CurrentVerbose = $VerbosePreference
- $VerbosePreference = 'silentlycontinue'
- $Result = Invoke-RestMethod @Splat
- } catch {
- Throw "Clearpass API Request failed: $($Error[0].ToString())"
- } finally {
- $VerbosePreference = $CurrentVerbose
- }
- return $Result
- }
- function Get-ClearpassChunkedResult {
- <#
- .SYNOPSIS
- Combine results from multiple API queries as Clearpass doesn't support unlimited result count in one request
- .DESCRIPTION
- Makes multiple calls to Invoke-ClearpassApi while there are still more results in the set, and returns
- all resutls in a combined array
- Request Method, Body and Headers are for Invoke-ClearpassAPI are omitted from this function as it's an
- implicit GET and Body/Headers aren't relevant
- .PARAMETER Path
- Array of strings for each segment in the URL path - passed to New-ApiUri
- .PARAMETER SetSize
- The number of results to get per query (default to 25)
- #>
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $false)]
- [string[]]$Path,
- [Parameter(Mandatory = $false)]
- [hashtable]$Query,
- $SetSize = 25
- )
- $Result = [System.Collections.ArrayList]@()
- $Query['offset'] = $null
- $Query['limit'] = $SetSize
- do {
- if($null -eq $Query['offset']){
- $Query['offset'] = 0
- } else {
- $Query['offset']+= $SetSize
- }
- Write-Debug "Performing chunked query for path: $($Path -join '/'). Offset: $($Query['offset'])"
- $RawResult = Invoke-ClearpassApi -Path $Path -Query $Query
- $Result.AddRange(@($RawResult.'_embedded'.'items'))
- } while($null -ne $RawResult.'_links'.'next')
- return $Result
- }
Advertisement
Add Comment
Please, Sign In to add comment