Home > Back-end >  PHP curl not working with dropbox OAuth, returns "invalid request"
PHP curl not working with dropbox OAuth, returns "invalid request"

Time:04-12

Dropbox documentation says to authenticate you have to do the following:

curl https://api.dropbox.com/oauth2/token \
    -d code=<AUTHORIZATION_CODE> \
    -d grant_type=authorization_code \
    -d redirect_uri=<REDIRECT_URI> \
    -u <APP_KEY>:<APP_SECRET>

Here is my attempt with PHP but dropbox returns following error invalid request - The request parameters do not match any of the supported authorization flows

$url = "https://api.dropbox.com/oauth2/token";
            $redirect_uri = 'https://www.mywebsite.com/oauth_dropbox';
           
            $postfields = array(
                'code' => $_GET['code'],
                'grant_type' => 'authorization_code',
                'redirect_uri' => $redirect_uri
            );

            $auth = "$app_key:$app_secret";
            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
            curl_setopt($curl, CURLOPT_USERPWD, $auth);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

            $json_response = curl_exec($curl);
            $responseObj = json_decode($json_response);

How do i solve?

CodePudding user response:

It looks like this works if you explicitly set Basic authorization, that is, instead of:

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

set this:

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

CodePudding user response:

Your current curl sends GET request (that's why external API does not see any parameters sent), but you are adding content as it's POST request. Add CURLOPT_POST too.

$url = "https://api.dropbox.com/oauth2/token";
$redirect_uri = 'https://www.mywebsite.com/oauth_dropbox';
           
$postfields = [
    'code' => $_GET['code'],
    'grant_type' => 'authorization_code',
    'redirect_uri' => $redirect_uri
];

$auth = "$app_key:$app_secret";
$curl = curl_init($url);

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
curl_setopt($curl, CURLOPT_USERPWD, $auth);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
$responseObj = json_decode($json_response);
  • Related