PHP POSTMAN Follow Authorization header Meaning

Viewed 27

I'm performing a POST request to a REST Service that requires an OAuth 2.0 authorization.

In Postman everything works perfectly fine since enabling the "Follow Authorization header" option so the auth header will be retained after a redirection. However I dont know the equivalent to that attribute for a CURL request in PHP. So therefore I still get the following error: "Session expired or invalid".

Does anyone know how to successfully keep the auth header after a redirection in PHP cURL?

This is my php code:

      $token = $this->getToken();
      $url = "XXX";

      $curl = curl_init();

      curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
      ,
      curl_setopt($curl, CURLOPT_POSTFIELDS, array(
        'client_id'     => 'XXX',
        'client_secret' => 'XXX',
        'username'      => 'XXX',
        'password'      => 'XXX',
        'grant_type'    => 'password',
        'redirect_uri'  => 'XXX'
      )))
    ));

    $response = curl_exec($curl);

    var_dump('TOKEN: ' . $token);
    var_dump($url);
    var_dump(curl_getinfo($curl));

    if (curl_errno($curl)) {
        var_dump('Error:' . curl_error($curl));
    } else {
        var_dump("SUCCESS! ");
        var_dump($response);
    }
1 Answers

You cannot do this:

 curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'client_id'     => 'XXX',
    'client_secret' => 'XXX',
    'username'      => 'XXX',
    'password'      => 'XXX',
    'grant_type'    => 'password',
    'redirect_uri'  => 'XXX'

You already did this: URLOPT_POSTFIELDS => json_encode($data),

And you cannot use an array if you want to keep the Content-Type: application/json.
When you use an array for POSTFIELDS, curl will override the content type with Content-Type: application/x-www-form-urlencoded



I sometimes use file_get_content() with a context.
This is an easy way (without SSL) to get the headers and post data right.
Keeping mind that file_get_content() has some of the same idiosyncrasies as curl. The context has file_get_content() which populates the Body.

<?php
header("Content-Type: text/plain,UTF-8");

$jsn = file_get_contents('json.jsn');
$postdata = http_build_query(
    array(
        'json' => $jsn,
    )
);
$opts = array('http' =>
  array(
    'method'  => 'PUT',
    'header'  => 'Content-type: application/json',
    'content' => $jsn  //useing JSON rather than $postdata
  )
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
echo $result;
Related