Get Started!

˂ Return to FAQ

Getting Started Guide using REST APIs in PowerShell with Xton Access Manager.

This page outlines several specific scenarios in which REST APIs in XTAM can be called using PowerShell scripts. Please note that security is strictly enforced, so ensure the account executing the scripts has the appropriate permissions to access the objects in XTAM.

Looking for REST API examples with Shell scripts? Click here to learn more.

The following scripts are provided as an example of what is possible, however they can and should be customized to meet your requirements including outside script integration, formatting and proper error handling.

 
 

Create a Record
Provides the ability to create a new record with the defined parameters.

$folderId="183320"   # ID of Parent Folder
$typeId = "1724"   #  ID of Record Type
$recordName = "Name"   # Record Name (required)
$recordDescription = "Description"  # Record Description (optional)

$rhost = "host.company.com"   # Host URL
$rport = "22"   # Host Port
$ruser = "user"   # Host User
$rpassword="myPassw0rd"   # Host Password

$rest = "$url/rest/record/new/$folderId/$typeId"

$Custom = '{{"Host":"{0}","Port":{1},"User":"{2}","Password":"{3}"}}' -f $rhost, $rport, $ruser, $rpassword

$Body = @{
    name = $recordName
    description = $recordDescription
    custom = $Custom
}

Invoke-RestMethod -Method Post  -ContentType 'application/x-www-form-urlencoded' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)" -Body $body

Write-Host Done

 
 

Create a Folder
Provides the ability to create a new folder with the defined parameters.

$folderId="183320"   # ID of Parent Folder
$folderName = "Name"   # Folder Name (required)
$folderDescription = "Description"   # Folder Description (optional)

$rest = "$url/rest/folder/create/$folderId"

$folder = @{
    name = $folderName
    description = $folderDescription
}

$body = $folder | ConvertTo-Json

Invoke-RestMethod -Method Post  -ContentType 'application/json' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)" -Body $body

Write-Host Done

 
 

Retrieve Root Folder
Provides the ability to retrieve the Root Folder (All Records) and its parameters including ID.

$rest = "$url/rest/folder/root"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 
 

List Folder Content
Provides the ability to list all content of the specified folder.

$folderId="183320"    # Folder ID

$rest = "$url/rest/folder/list/$folderId"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 
 

Retrieve a Record
Provides the ability to retrieve all the parameters of an existing record excluding the password.

$recordId="168351"   # Record ID

$rest = "$url/rest/record/get/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json

Write-Output "$($secret.name): $($custom.User) / $($custom.Password)"

Write-Output $secret
Write-Output $custom
Write-Host Done

 
 

Retrieve a Record with Password (Unlock)
Provides the ability to retrieve all the parameters of an existing record including the password.

$recordId="168351"   # Record ID

$rest = "$url/rest/record/unlock/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json

Write-Output "$($secret.name): $($custom.User) / $($custom.Password)"

Write-Output $secret
Write-Output $custom
Write-Host Done

 
 

Retrieve a Record Field (Unlock)
Provides the ability to retrieve a single parameter from a record’s field including the password.

$recordId="168351"   # Record ID
$field="Password"   # The (internal) Name of the field

$rest = "$url/rest/record/unlock/$recordId/" + $field

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Output "$($field): $($secret)"
Write-Host Done

 
 

Update a Record
Provides the ability to update an existing record.

$recordId="183323"   # Record ID
$RecordName = "Updated Name"   # Updated Record Name
$RecordDescription = "Updated Description"   # Updated Record Description

$rhost = "host1.company.com"   # Updated Host URL
$rport = "3389"   # Updated Host Port
$ruser = "user1"   # Updated Host User
$rpassword="myPassw0rd1"   # Updated Host Password

$password = $mycreds.GetNetworkCredential().password

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/record/update/$recordId"

$Custom = '{{"Host":"{0}","Port":{1},"User":"{2}","Password":"{3}"}}' -f $rhost, $rport, $ruser, $rpassword

Write-Host $Custom

$Body = @{
    name = $RecordName
    description = $RecordDescription
    custom = $Custom
}

Invoke-RestMethod -Method Put  -ContentType 'application/x-www-form-urlencoded'  -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken} -Uri "$($rest)" -Body $body

Write-Host Done

 
 

Download a File
Provides the ability to download a file (certificate, SSH key, secured file) associated to a record.

$recordId="183323"   # Record ID
$fieldName = "Cert"   # Internal Name of Field that contains the file

$rest = "$url/rest/record/unlock/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json
$file= $custom.$fieldName
$fileName= $file.name

$dwnld = "$url/rest/content/record/$recordId/$fieldName"
$output = "C:\Folder\" + $fileName   # Save To Location

Invoke-WebRequest -Credential $mycreds -Uri $dwnld -OutFile $output

Write-Output Done

 
 

Share a Record or Folder
Provides the ability to share a record or folder with other users or groups.

$shareUser = "user"   # Share object with User or Group Login

$rest = "$url/rest/user/ensure/$shareUser"
$shareUserId = Invoke-RestMethod -Method Get  -ContentType 'application/x-www-form-urlencoded' -Credential $mycreds -Uri "$($rest)"

$objectId="186460"   # Record or Folder ID to Share
$userId = $shareUserId.id
$recordControl = "View"   # Permission Options: View / Unlock / Edit / Admin
$sessionControl = "None"   # Permission Options: None / Recording / Connect
$taskControl = "None"   # Permission Options: None / Execute / Review / Manage

$rest = "$url/rest/permissions/share/$objectId/$userId/$recordControl/$sessionControl/$taskControl"

Invoke-RestMethod -Method Post  -ContentType 'application/json' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 
 

Delete a Record
Provides the ability to delete an existing record.

$recordId="186008"   # Record ID to Delete
$folderId="183320"   # Parent Folder ID

$password = $mycreds.GetNetworkCredential().password

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/record/delete/$folderId/$recordId"

Invoke-RestMethod -Method Delete -ContentType 'application/json' -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 
 

Search for Objects (Record or Folder)
Provides the ability to search for existing records or folders.

$searchTerm = "object name"   # Value to Search

$rest = "$url/rest/record/find/View/$searchTerm"

$secret=Invoke-RestMethod -Method Get  -ContentType 'application/json'  -Credential $mycreds -Uri "$($rest)"

Write-Host Results:
foreach ($results in $secret){ 
Write-Host "Object Name:" $results.name "( Object ID:" $results.id")"
}

Write-Host Search Complete

 
 

List Record Types
Provides the ability to output a list of all currently available Record Types.

$rest = "$url/rest/recordtype/list"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 
 

Database Export (Decrypted)
Provides the ability to export the XTAM database to a decrypted file(s).

$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/export/false"

Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 
 

Database Export (Encrypted)
Provides the ability to export the XTAM database to an encrypted file(s).

$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/export/true"

Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 
 

Database Import
Provides the ability to import an exported XTAM database file.

$exportName="xtamexp-20180313152316-120"  # Export file name

$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/import/$exportName"
Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 
 


API Token
To provide protection against Cross-Site Request Forgery (CSRF) attacks each XTAM API function that changes something in the system (mostly, POST, PUT and DELETE REST methods) requires an API Token passed using X-XSRF-TOKEN header. To obtain a token, an XTAM REST client has to request it from XTAM server by calling /rest/user/whoami function that sets XSRF-TOKEN cookie with the value of the token. Below is the example of PowerShell functions that obtain the API token from XTAM server by the server base URL and credentials (ApiToken) or a session (ApiTokenCas) objects depending on the style of the authentication. See examples of using this token in the code samples above.

Function ApiTokenCas() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $session,
        [Parameter(Mandatory=$true)] $url
    )

    process {
		$rest = "$url/rest/user/whoami"
		$resp=Invoke-RestMethod -WebSession $session -Method Get -Uri $rest -MaximumRedirection 5

		$session.Cookies.getCookies($rest) | % { if ($_.Name -eq 'XSRF-TOKEN') { $apiToken = $_.Value } }
		return $apiToken
    }
}

Function ApiToken() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $creds,
        [Parameter(Mandatory=$true)] $url
    )

    process {
		$rest = "$url/rest/user/whoami"
		$resp=Invoke-RestMethod -Credential $creds -Method Get -Uri $rest -MaximumRedirection 5

		$session.Cookies.getCookies($rest) | % { if ($_.Name -eq 'XSRF-TOKEN') { $apiToken = $_.Value } }
		return $apiToken
    }
}

 

API token enforcement could be disabled by defining parameter xtam.api.token.verification=false

 


Secure Authentication
XTAM provides several methods for authenticating, first is a standard, non-federated username and password login, the second is a more robust federated login experience that supports multi-factor authentication and additional options and the third is using Authentication Tokens. Depending on how your XTAM installation is configured, the following authentication methods will be used.
 

Standard Authentication (non-federated)
If your login experience to XTAM is a simple prompt like the one shown below, then you will use the following to authenticate using our REST APIs.

XTAM Non-federated simple Login Prompt

$url= "http://localhost:8080/xtam"   # XTAM URL
$user = "admin"   # XTAM User

$mycreds= Get-Credential $user

# Your code starts here
Invoke-RestMethod ...   # Non-Federated Authentication Invoke-RestMethod cmdlet

 

Federated Authentication
If your login experience to XTAM is a federated sign-in page like the one shown below, then you will use the following to authenticate using our REST APIs.

XTAM Federated Login Prompt

Function CasAuth() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $Base,
        [Parameter(Mandatory=$true)] $CasBase,
        [Parameter(Mandatory=$true)] $UserName,
        [Parameter(Mandatory=$true)] $Password
    )

    process {
        # post credentials
        $body=@{username=$UserName;password=$Password}
        $resp=Invoke-WebRequest -Method Post -Uri "$($CasBase)/v1/tickets" -Body $body -SessionVariable 'session'

        # get service ticket
        If($resp.Headers.Location.GetType() -Eq [string]) {
	        $st=Invoke-WebRequest -Method Post -Uri $resp.Headers.Location -Body "service=$($Base)/"
        } Else {
	        $st=Invoke-WebRequest -Method Post -Uri $resp.Headers.Location[0] -Body "service=$($Base)/"
        }

        # get authenticated session using service ticket
        $resp=Invoke-WebRequest -Uri "$($Base)/?ticket=$($st.Content)" -SessionVariable 'session'

        return $session
    }
}

$url="https://xtam.company.com/xtam"   # XTAM URL
$cas_url="https://xtam.company.com/cas"   # XTAM Signin Page URL

$user = "admin"   # XTAM User

$mycreds=Get-Credential $user
$password=$mycreds.GetNetworkCredential().password
$session=CasAuth -Base $url -CasBase $cas_url -UserName $user -Password $password

# Your code starts here
Invoke-RestMethod -WebSession $session ...   # Federated Authentication Invoke-RestMethod cmdlet requires a web request session

 

Token Authentication
If you are using Authentication Tokens, then you will use the following to authenticate using our REST APIs.
Function TokenAuth() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $Base,
        [Parameter(Mandatory=$true)] $CasBase,
        [Parameter(Mandatory=$true)] $Token
    )

    process {
       $resp=Invoke-WebRequest -Method Get -Uri "$($CasBase)/login?service=$Base/" -Headers @{"token"="$Token"} -SessionVariable 'session' -UseBasicParsing -MaximumRedirection 0 -ErrorAction Ignore
       If($resp.Headers.Location.GetType() -Eq [string]) {
          $loc=$resp.Headers.Location
       } Else {
          $loc=$resp.Headers.Location[0]
       }
       $resp=Invoke-WebRequest -Uri "$loc" -SessionVariable 'session'
       return $session
    }
}

$url="https://xtam.company.com/xtam"   # XTAM URL
$cas_url="https://xtam.company.com/cas"   # XTAM Signin Page URL

$token = "yourXTAMtoken"   # XTAM Token

$session=TokenAuth -Base $url -CasBase $cas_url -Token $token

# Your code starts here
Invoke-RestMethod -WebSession $session ...   # Token Authentication Invoke-RestMethod cmdlet requires a web request session

 
 

Copyright © 2018 Xton Technologies, LLC. All rights reserved.