Home > OS >  Manage credentials for Invoke-RestMethod request
Manage credentials for Invoke-RestMethod request

Time:04-15

I'm writing a PowerShell script to query an application API (Qualys), and the first step is to authenticate. I can only do it unsecurely:

[string]$username = "username"
[string]$password = "superpassword"

$hdrs= @{"X-Requested-With"="Powershell"}

$base = "https://application-base-url/api/2.0/fo"
$body= "action=login&username=$username&password=$password"
Invoke-RestMethod -SessionVariable sess -Headers $hdrs -URI "$base/session/" -Method POST -Body $body 

It works, but as you can see, the username & password are stored in the file. I would like Powershell to prompt me the username and password, and use it to authenticate while securely manage them.

I tried to use Get-Credential but I couldn't make it work. Could anyone help?

CodePudding user response:

Apparently you need to put the plain-text password in the body.

To retrieve that from a credential object you get from using Get-Credential, use:

$cred = Get-Credential

$username = $cred.UserName
$password = $cred.GetNetworkCredential().Password  # --> the password as plain-text
  • Related