A couple weeks back when Horizon 8 was released they also made us happy with the Swagger page to browse the rest api methods. One thing it lacks though is a way to easily authenticate to actually try them. There is an Authenticate button but I couldn’t find any information on what it actually needs. While creating my previous blog post I was messing around with things and actually found a way to authenticate. First I tried to authenticate using the actual api method for that but trying any call afterwards still showed me as not being authenticated. You could copy/paste the access token though and you’ll see in the script how that might work, or check the 3rd screenshot.
the swagger can be found like this: https://loftcbr01.loft.lab/rest/swagger-ui.html
Let’s have a look at the script.
$url = read-host "url for connectionserver" $username=read-host "Username" $domain=Read-host "Domain" $password=read-host "Password" -AsSecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) function Get-HRHeader(){ param($accessToken) return @{ 'Authorization' = 'Bearer ' + $($accessToken.access_token) 'Content-Type' = "application/json" } } function Open-HRConnection(){ param( [string] $username, [string] $password, [string] $domain, [string] $url ) $Credentials = New-Object psobject -Property @{ username = $username password = $password domain = $domain } return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json) } function Close-HRConnection(){ param( $accessToken, $url ) return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json) } try{ $accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $url Set-Clipboard (Get-HRHeader -accessToken $accessToken).Authorization } catch{ write-host "Error while authenticating" }
To make it directly usable I have chosen to ask for web address of the server, username, domain and password and in the end I copy the token you need to the clipboard for you. Let’s have a look at it
No further output but I can paste what I have in the clipboard now in the Authenticate field at the swagger page, hit authorize and close.
And now I can try api calls, pulling machines from the inventory for example.
SO that’s how we can actually use the Swagger page to try api calls.
Pingback: Using the Horizon 8 swagger page | For servers