OAUTH2 API Attachment - Powershell
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-10-2024 03:45 AM
Hi all,
I am needing help regarding adding an attachment/image to a RITM.
I need to use adaptive auth first to connect and then run the script to attach the file (is the adaptive auth still needed?) Please note this needs to be a multipart and not base64 which is where I could be going wrong.
I am attempting to attach a .png file to a RITM and I am using the following script;
#For getting access token you can use this code:
$username = “<Username>”
$password = '<Password>'
$ClientID = “<Client ID>”
$ClientSecret = “<Client Secret”
$RestEndpoint = ‘https://<URL>.service-now.com/oauth_token.do’
$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=password&username=’+$username+’&password=’+$password+’&client_id=’+$ClientID+’&client_secret=’+$ClientSecret)
$headers = @{
'Content-Type' = 'application/json'
'Accept' = 'application/json'
}
$result = Invoke-RestMethod -Uri $RestEndpoint -Body $Body -Headers $headers -ContentType ‘application/x-www-form-urlencoded’ -Method Post
$access_token = $result.access_token
# Eg. User name="admin", Password="admin" for this code sample.
$user = "<Username>"
$pass = "<Password>"
# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','multipart/form-data')
# Specify endpoint uri
$uri = 'https://<URL>.service-now.com/api/now/attachment/file?table_name=sc_req_item&table_sys_id=<RITM Sys ID>&file_name=ScreenshotTest.png'
# Specifiy file to attach
$fileToAttach = 'c:\Temp\ScreenshotTest.png'
# Specify HTTP method
$method = "POST"
# Send HTTP request
$response= Invoke-RestMethod -Headers $headers -Uri $uri -Method $method -InFile $fileToAttach
# Print response
$response.RawContent
With the above script I receive the following error;
Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At line:47 char:12
+ $response= Invoke-RestMethod -Headers $headers -Uri $uri -Method $met ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand