php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Php curl doesnt redirect

Open ejgutierrez74 opened this issue 4 years ago • 12 comments

Description

The following code or in general any public api like spotify, twitter that sends a response with redirect url:


session_start();

ob_start();


function random() {
    return (float)rand()/(float)getrandmax();
  }

/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
function generateRandomString ( $length) 
{
    $text = '';
    $possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
    for ($i = 0; $i < $length; $i++) {
      $text[$i]=$possible[intval(floor(random() * strlen($possible)))];
    }
    return base64_encode($text);
  };


/* *The userid and password are separated by a single colon (":") character within a base64 encoded string in the credentials.

If the user agent wishes to send the Client ID "Aladdin" and password "open sesame,” it would use the following header field:
      
Authorization: Basic SECRET== 

To create the basic authorization header you will need to base64 encoding on your Client ID and Client Secret which can be 
obtained from your App’s “Keys and Tokens” page inside of the developer portal.*/
   
$client_id='SECRET';

$client_secret='SECRET';

$authorizationHeader = 'Authorization: Basic ' . base64_encode($client_id . ':' . $client_secret);


/*
Steps to connect using OAuth 2.0
Step 1: Construct an Authorize URL

Your App will need to build an authorize URL to Twitter, indicating the scopes your App needs to authorize. 
For example, if your App needs to lookup Tweets, users and to manage follows, it should request the following scopes:

tweet.read%20users.read%20account.follows.read%20account.follows.write

The URL will also contain the code_challenge and state parameters, in addition to the other required parameters. 
In production you should use a random string for the code_challenge.

*/

$code_challenge = generateRandomString(8);
$_SESSION['codechallengesaved']=$code_challenge;

//state tb random ???
$state= 'state';
$_SESSION['statesaved']=$state;

//%20 sino en espacio en blanco. si quieres offline acces se lo añades, si no por defecto no pones nada y es online access
$scope="tweet.read users.read follows.read follows.write offline.access";
//$scope="tweet.read%20users.read%20account.follows.read%20account.follows.write%20offline.access";

/*
Step 2: GET oauth2/authorize

Have the user authenticate and send the application an authorization code. If you have enabled OAuth 2.0 for your App 
you can find your Client ID inside your App’s “Keys and Tokens” page.

An example URL to redirect the user to would look like this:

https://twitter.com/i/oauth2/authorize?response_type=code
                        &client_id=SECRET
                        &redirect_uri=https://www.example.com
                        &scope=tweet.read%20users.read%20follows.read%follows.write
                        &state=state
                        &code_challenge=challenge
                        &code_challenge_method=plain
*/ 
$endpoint='https://twitter.com/i/oauth2/authorize';
//$redirect_uri='http://localhost:8080/callback/logintwitter.php';
$redirect_uri='https://votacionya.000webhostapp.com/callback/logintwitter.php';
//$redirect_uri='http://127.0.0.1:8080/callback/logintwitter.php';

$url = $endpoint . '?' . 'response_type=' . 'code'
                       . '&client_id=' . $client_id 
                       . '&redirect_uri=' . rawurlencode($redirect_uri) 
                       . '&scope=' . rawurlencode($scope) 
                       . '&state=' . $state 
                       . '&code_challenge=' . $code_challenge 
                       . '&code_challenge_method=' . 'plain';

//Inicio curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    //No se mucho que hacen estas opciones pero funcionan
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


//resultado de peticion
$result = curl_exec($ch);

//Gestion de errores
if (curl_errno($ch)) {
    print "Error: " . curl_error($ch);
    echo 'Error en ch curl';
} else {
    // Show me the result Info de la peticion CURL ...se podria quitar mas adelante
    echo 'ch curl Info';
    echo '<h4> Info Curl </h4>';
    $info = curl_getinfo($ch);

    echo '</br>';
    echo '<pre>' . print_r($info, true) . '</pre>';
     

    $json = json_decode($result);

    //Resultado consulta...puedo acceder de la forma json->access_token
    echo '</br>';
    echo '<h2> Resultado consulta </h2>';
    echo '<pre>' . print_r($json, true) . '</pre>';
    echo '<pre>' . print_r($json->code, true) . '</pre>';
    echo '<pre>' . print_r($json->state, true) . '</pre>';
    echo '</br>';

    var_dump($result);

         
    }

    //Cierro CURl
    curl_close($ch);
//Importante dode reenviO, EL REDIRECT URI ha de coincidir con el redirect de tu aplicacion
 // header('Access-Control-Allow-Origin : *');
  header('Location: '.$url);
  ob_end_flush();

Resulted in this output: Spotify API have to redirect to the uri. Instead you have to insert header('Location: '.$url); at the end, that is the instruction that redirects you.

But I expected this output instead: php curl should receive the data from spotify api or whatever, and redirect to the url

Edit: Added as suggested curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); without header location, and still doesnt work

PHP Version

7.4

Operating System

No response

ejgutierrez74 avatar Jan 07 '22 19:01 ejgutierrez74

I can't tell what bug you're trying to report.

If you want the user to follow the OAuth process then yes: you must redirect the user to that URL. If you want your server to follow the OAuth process then I'm not sure what problem you have but it might be solved by recognizing that cURL needs the CURLOPT_FOLLOWLOCATION flag if you want it to follow redirects.

damianwadley avatar Jan 07 '22 22:01 damianwadley

@ejgutierrez74 As @damianwadley suggested, you need to add the following line to your code somewhere after the curl_init and before the curl_exec:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

This will make curl make another request when encountering a 30x response instead of returning that response directly.

Also please not that it might not be a smart idea to share your various secrets on the internet. Secrets / API Keys are intended for only your eyes. If you share them other people will be able to login with your user and do harmful things.

iluuu1994 avatar Jan 07 '22 22:01 iluuu1994

Thanks for your help. About secrets dont get worried is only for educational purpose. If necessary id delete the app or regenerate keys.

Id try this solution: 👍 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

@damianwadley In theory, or as far as i know, when you execute curl instruction in spotify api for example in terminal, it redirects to the page needed. Instead if you tranlate the curl terminal command to php-curl, as mentioned it gets stuck and doesnt redirect to the url. This step is mandatory for the user to authorize the app work with the api, Ive tried with spotify and twitter, and in both cases it doesnt redirect. I have no clear if its problem of php or twitter or whatever api, but i think it could be a php-curl because with curl in command line it works.

Id try the solution and report, in the next days

ejgutierrez74 avatar Jan 08 '22 19:01 ejgutierrez74

Id try the solution and report, in the next days

Thanks! Switching to feedback status for the time being.

cmb69 avatar Jan 08 '22 20:01 cmb69

I can confirm still doesnt work...it doesnt redirect to the authorise page of twitter in this case. I also tested it in spotify.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

i still have to add: header('Location: '.$url); to redirect the user to authorization page....

Id update code in original post.

ejgutierrez74 avatar Jan 09 '22 12:01 ejgutierrez74

Then I refer back to what I said earlier:

If you want the user to follow the OAuth process then yes: you must redirect the user to that URL.

damianwadley avatar Jan 09 '22 14:01 damianwadley

I also want to note that using rand() to generate the code_challenge is a terrible idea. Use random_bytes() instead.

cmb69 avatar Jan 09 '22 14:01 cmb69

Then I refer back to what I said earlier:

If you want the user to follow the OAuth process then yes: you must redirect the user to that URL.

So i have to put the header location and in your opinion is right ? dont have php-curl at time making that request should redirect to the redirect_url, as redirect_url is passed as a parameter. In my opinion and as for ive read, the curl makes a request, that brings you to a page whre you authorise or not the app to use your credentials in twitter, spotify access.... If you execute the code without header location, this never happens and though you dont get the tokens to continue. I havent seen any tutorial that says that after executing curl, you have to execute an instruction to go to that page....as in real terms you are repeating the same request twice...with same endpoint, params, and headers.

ejgutierrez74 avatar Jan 09 '22 15:01 ejgutierrez74

I also want to note that using rand() to generate the code_challenge is a terrible idea. Use random_bytes() instead.

thanks, can you explain a little better why ? And whats the difference ?? Rand generates an a random integer, but random_bytes generates pseudo-random bytes .... isnt better to get random than pseudo random ? im a newbie here....;)

ejgutierrez74 avatar Jan 09 '22 15:01 ejgutierrez74

@ejgutierrez74 From the docs:

https://www.php.net/manual/en/function.rand.php

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

iluuu1994 avatar Jan 09 '22 15:01 iluuu1994

@ejgutierrez74, I think you're better off to contact any of the documented support channels or stackoverflow.com (I don't understand why that is not mentioned on that page).

cmb69 avatar Jan 09 '22 15:01 cmb69

I did: https://stackoverflow.com/questions/70567314/oauth2-twitter-api-php-curl-returns-null In my opinon it has no sense to make the request twice. As curl you only need one.

Sorry but in twitter api they think that is php-curl problem, because they are working fine with curl and other languages....

@cmb69 please execute the code above, is the only need to test, just comment line header and then execute with header line, perhpaps you could understand better, as my english is not good....

ejgutierrez74 avatar Jan 09 '22 15:01 ejgutierrez74