0

I am trying to connect to an API with Powershell using Invoke-RestMethod, but I keep running into an error for invalid credentials. I am converting the -Body to JSON in my API call. The documentation states there is no header and only 2 parameters: the username and password. I am also using -ContentType application/json, although I believe the issue lies with the JSON and not the Powershell itself.

The API has a test on their website where you can input your credentials to get an API key, which works fine so I know the credentials are correct. They also have a textbox to test authentication with JSON, which throws an error. The JSON I am testing looks like this:

{
    "username": "myusername",
    "password": "xxxxxxxx"
}

The API documentation also provides a sample PHP script to get an API key, which I confirmed does work when I put my credentials into it. The sample script is below:

$url = "https:website.com/api";
$content = ["username"=>"myusername","password"=>"********"];
$curl = curl_init($url);
if($curl) {
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // POST method
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($content));

    $json_response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    $response = json_decode($json_response, true);
} else {
    die("failed to connect\n");
}

I am not a PHP developer, but after looking up every command I believe I understand what it is doing for the most part. I am just wondering if I am missing anything in my JSON that the PHP script might add. In the PHP script I did convert the $content variable to JSON and it is identical to the JSON provided above, as well as the JSON used in the Powershell command.

As a side note, I have also tested it with with a SecureString in Powershell, which yielded the same results. Once I get the JSON to work I am planning on using a SecureString.

Any kind of assistance would be very helpful. Thank you!

Andrew Draper
  • 101
  • 1
  • 9
  • The PHP script is not sending the credentials as JSON, it is sending as an http query string, ie `username=myusername&password=12345`. This questions looks relevant for formatting it in Powershell: https://stackoverflow.com/questions/17325293/invoke-webrequest-post-with-parameters – cOle2 May 27 '22 at 15:44
  • That worked wonders, thank you. I guess the documentation was misleading by prompting for a JSON input – Andrew Draper May 27 '22 at 17:58

0 Answers0