Search code examples
phptwitteroauthtwitter-oauththephpleague

Could not authenticate temporary credentials for Twitter Oauth


I am able to get temporary credentials and able to get oauth token, but when I do use the returned token to fetch user details, I'm unable to fetch it thus the error.

I am using thephpleague/oauth1-client package and created a simple controller where I followed their Twitter Sample. From this, I am getting this error

League\OAuth1\Client\Credentials\CredentialsException: Received HTTP status code [401] with message "{"errors":[{"code":32,"message":"Could not authenticate you."}]}" when getting temporary credentials. in /var/www/html/PF.Site/Apps/TipsMarketplace/vendor/league/oauth1-client/src/Client/Server/Server.php:418

and here is the sample code I've created.

        $server = new Twitter(array(
            'identifier' => 'my-identifier',
            'secret' => 'my-secret',
            'callback_uri' => "http://localhost:8080/twitter/auth",
        ));

        session_start();
        if (isset($_GET['user'])) {
            $tokenCredentials = unserialize($_SESSION['token_credentials']);

            $user = $server->getUserDetails($tokenCredentials);
            var_dump($user);
        } elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
            $temporaryCredentials = unserialize($_SESSION['temporary_credentials']);

            $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);

            unset($_SESSION['temporary_credentials']);
            $_SESSION['token_credentials'] = serialize($tokenCredentials);
            session_write_close();

            header("Location: http://{$_SERVER['HTTP_HOST']}/twitter/auth?user=user");
            exit;
        } elseif (isset($_GET['denied'])) {
            echo 'Hey! You denied the client access to your Twitter account!';
        }

        $temporaryCredentials = $server->getTemporaryCredentials();

        $_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
        session_write_close();

        $server->authorize($temporaryCredentials);

Solution

  • It turns out that I did not followed the 3-legged Oauth by twitter which is also indicated in the sample from the library.

    In my code above, I've skipped the $server->authorize($temporaryCredentials) wherein it will show the Authorization Page/Login page of twitter.