John Hubler
John Hubler

Reputation: 909

API request working in Postman, but not working in PHP script (The request body must contain the following parameter: 'grant_type')

I have an API request that I am trying to get a token from.

In Postman, the call works without issue, and I get a response with a token.

However, when I grab the code that is produced by Postman (that uses the same settings), I get the following error:

{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 096b2d08-2a58-46b9-80a1-701867418c00\r\nCorrelation ID: c96623e2-475f-48c5-bced-a1e87a557705\r\nTimestamp: 2023-05-08 16:01:55Z","error_codes":[900144],"timestamp":"2023-05-08 16:01:55Z","trace_id":"096b2d08-2a58-46b9-80a1-701867418c00","correlation_id":"c96623e2-475f-48c5-bced-a1e87a557705","error_uri":"https://login.microsoftonline.com/error?code=900144"}

This is unusual for me, because I have the grant_type clearly in the body parameters.

Here is my PHP code:

<?php
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.myendpoint.com/api/oauth2/v2.0/token',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array(
            'client_id' => '--hidden-for-obvious-reasons--',
            'client_secret' => '--hidden-for-obvious-reasons--',
            'grant_type' => 'client_credentials',
            'scope' => 'https://api.myendpoint.com/.default'
        ),
        CURLOPT_HTTPHEADER => array(
        'Content-Type: application/x-www-form-urlencoded',
        'Ocp-Apim-Subscription-Key: hidden-for-obvious-reasons'
        ),
    ));

    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        echo 'cURL Error: ' . curl_error($curl);
        exit;
    }

    curl_close($curl);

    echo "<pre>$response</pre>";
?>

I "thought" it might be because I am testing the script locally, and that the endpoint might require the request to come from https:// – however, when I uploaded to my server, it produced the same error.

I also found this thread: https://stackoverflow.com/questions/52129890/get-curl-request-only-works-in-postman-but-not-in-php and tried many of the suggestions from there, but nothing seemed to do the trick there either.

Any ideas what I might be missing, or why it might not be picking up the grant_type in the body?

Upvotes: 0

Views: 853

Answers (1)

John Hubler
John Hubler

Reputation: 909

@Professor Abronsius's comment was right. I just needed to change the content-type from application/x-www-form-urlencoded to multipart/form-data, and that did the trick.

Upvotes: 1

Related Questions