Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How can we pass credentials in a secure way in powershell script for connecting to Service now uisng rest api.

So199787
Kilo Contributor

I have a power shell script for upload attachment to Service now incident using Rest api.

In the script I have to pass username and password in a secure way instead of harded coded values.

 

Below is the script using.

$user = "xxx"
$pass = "xx"

# 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','application/json')
# $headers.Add('Content-Type','text/plain')

# Specify endpoint uri

$uri = "https://xx-now.com/api/now/attachment/file?table_name=xx&table_sys_id=xxx&file_name=xxx.pdf"

# Specifiy file to attach
$fileToAttach = "xxx"

# Specify HTTP method (POST, PATCH, PUT)
$method = "POST"

# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -InFile $fileToAttach

# Print response
$response.RawContent

Can some one help.

5 REPLIES 5

Rogers Cadenhe1
Giga Guru

It looks like your script is adding a basic authentication header to the request. What is the error you're encountering?

So199787
Kilo Contributor

There is no error currently. Here I modified the script to pass username, password, uri and filetoAttach as parameters.

As we have a security constraint, we have to pass the password parameter in a secured way to script. 

So how can we pass the password in a secured way as parameter to the above powershell script?

Thanks in advance.

Tommy Jensen
Giga Guru

right now this is how I am passing values in script.

$user="xx"

$pass = "xx"


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

# Set proper headers

$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))

 

Tried to modify the value of $pass as below

$pass = Get-Content "C:\test\password.txt" | ConvertTo-SecureString

 

Now how to modify the below statement?

$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))

 

Can someone suggest?