简体   繁体   中英

Manage credentials for Invoke-RestMethod request

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM