简体   繁体   中英

Oauth tokens storing in mysql database does not work but works fine when using sessions

I'm trying to create app with 4shared API but to use it I need to authorize in 4shared using Oauth. The problem is that when I'm using sessions to store oauth_token everything works fine, but when Im trying to store tokens in Mysql database I'm getting error:

OAuthException:  No server with consumer_key "MY_CONSUMER_KEY" has been registered (for this user)object(OAuthException2)#3 (7) {
  ["message":protected]=>
  string(98) "No server with consumer_key "MY_CONSUMER_KEY" has been registered (for this user)"
  ["string":"Exception":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(68) "/usr/share/nginx/4shared/library/store/OAuthStoreSQL.php"
  ["line":protected]=>
  int(453)
  ["trace":"Exception":private]=>
  array(2) {
    [0]=>
    array(6) {
      ["file"]=>
      string(63) "/usr/share/nginx/4shared/library/OAuthRequester.php"
      ["line"]=>
      int(155)
      ["function"]=>
      string(9) "getServer"
      ["class"]=>
      string(13) "OAuthStoreSQL"
      ["type"]=>
      string(2) "->"
      ["args"]=>
      array(2) {
        [0]=>
        string(32) "MY_CONSUMER_KEY"
        [1]=>
        int(0)
      }
    }
    [1]=>
    array(6) {
      ["file"]=>
      string(46) "/usr/share/nginx/4shared/index.php"
      ["line"]=>
      int(52)
      ["function"]=>
      string(19) "requestRequestToken"
      ["class"]=>
      string(14) "OAuthRequester"
      ["type"]=>
      string(2) "::"
      ["args"]=>
      array(3) {
        [0]=>
        string(32) "MY_CONSUMER_KEY"
        [1]=>
        int(0)
        [2]=>
        array(3) {
          ["scope"]=>
          string(28) "https://api.4shared.com/v1_2"
          ["xoauth_displayname"]=>
          string(13) "Oauth 4Shared"
          ["oauth_callback"]=>
          string(41) "https://example.com/4shared/index.php"
        }
      }
    }
  }
  ["previous":"Exception":private]=>
  NULL
}

I have created proper mysql database and imported mysql.sql file into it from Oauth's store folder. Also If I'm not using 'conn' as an Option it does not connect to database at all, but I'm able to connect to DB with 'conn' option.

Here is my code:

include_once "library/OAuthStore.php";
include_once "library/OAuthRequester.php";

define("FOURSHARED_CONSUMER_KEY", "MY_CONSUMER_KEY");
define("FOURSHARED_CONSUMER_SECRET", "MY_SECRET_KEY");
define("FOURSHARED_OAUTH_HOST", "https://api.4shared.com");
define("FOURSHARED_OAUTH_HOST_SEARCH", "https://search.4shared.com");
define("FOURSHARED_REQUEST_TOKEN_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/initiate");
define("FOURSHARED_AUTHORIZE_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/authorize");
define("FOURSHARED_ACCESS_TOKEN_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/token");
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));


define("FOURSHARED_OAUTH_CALLBACK", "https://example.com/4shared/index.php");    

//  Inicia o OAuthStore
$options = array(
    'consumer_key' => FOURSHARED_CONSUMER_KEY, 
    'consumer_secret' => FOURSHARED_CONSUMER_SECRET,
    'server_uri' => FOURSHARED_OAUTH_HOST,
    'request_token_uri' => FOURSHARED_REQUEST_TOKEN_URL,
    'authorize_uri' => FOURSHARED_AUTHORIZE_URL,
    'access_token_uri' => FOURSHARED_ACCESS_TOKEN_URL,
    //'server' => 'localhost',
    //'username' => 'oauth',
    //'password' => 'password',
    //'database' => 'oauth',
    'conn' => new mysqli('localhost','oauth','password','oauth')
);

// Store token in database or sessions
// Choose a database.
OAuthStore::instance("MySQLi", $options);

try
{
    //  Step 1: If there is not an OAuth token yet, we need one.
    if (empty($_GET["oauth_token"]))
    {
        $getAuthTokenParams = array(
            'scope' => FOURSHARED_OAUTH_HOST . '/v1_2',
            'xoauth_displayname' => 'Oauth 4Shared',
            'oauth_callback' => FOURSHARED_OAUTH_CALLBACK
        );

        // Request a request token
        $tokenResultParams = OAuthRequester::requestRequestToken(FOURSHARED_CONSUMER_KEY, 0, $getAuthTokenParams);

        // Redirects to the authorization page. Here the user will give you permissions the first time and then be redirected back to your site.
        header("Location: " . FOURSHARED_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token']);
    }
    else {
        //  Step 2: Request an access token
        $oauthToken = $_GET["oauth_token"];
        $tokenResultParams = $_GET;

        try {
            OAuthRequester::requestAccessToken(FOURSHARED_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
        }
        catch (OAuthException2 $e)
        {
            var_dump($e);
            return;
        }
        // We will request user information
        $request = new OAuthRequester(FOURSHARED_OAUTH_HOST_SEARCH . '/v1_2/files', 'GET', $tokenResultParams);
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            // Convert string to json object
            $files_result = json_decode($result['body']);

            // Print the screen on the e-mail;
            print_r($files_result);
        }
        else {
            echo 'Error';
        }
    }
}
catch(OAuthException2 $e) {
    echo "OAuthException:  " . $e->getMessage();
    var_dump($e);

}

Everything works fine when im changing OAuthStore::instance("MySQLi", $options); to OAuthStore::instance("sessions", $options);

As requested by commenter: MySQL version: mysql Ver 14.14 Distrib 5.7.19, for Linux (x86_64) using EditLine wrapper

my.cnf content (tho I have many other databases on same server and those are working fine so shouldn't be problem with that):

[mysqld]

# Basic configuration
port=3306
server_id=0

datadir=/var/lib/mysql
tmpdir=/var/lib/mysqltmp
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

# Logging
log_error=/var/log/mysqld-error.log
slow_query_log=ON
slow_query_log_file=/var/log/mysqld-slow.log
general_log=OFF
general_log_file=/var/log/mysqld-general.log

# Remove leading # and set to the amount of RAM for the most important data cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. Default is 128M.
#innodb_buffer_pool_size = 128M

# Set the number of open tables. This has a huge effect on memory usage. Default value is 2000.
#table_open_cache=2000

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
#log_bin

# Optionally change the SQL mode.
#sql_mode=ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

# Remove leading # to set options mainly useful for reporting servers. The server defaults are faster for transactions and fast SELECTs. Adjust sizes as needed, experiment to find the optimal values.
#join_buffer_size = 128M
#sort_buffer_size = 2M
#read_rnd_buffer_size = 2M

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

Im also linking to a file with wich I created the database (this is file provided by oauth): https://pastebin.com/2eb0aTbL

Hi I think you are creating instance not properly.

can you check below link for a various example of Oauth Instance Creation?

php-oauthstore-instance-method-examples

function get_db_options()
{
    return array('server' => DB_HOST, 'username' => DB_USERNAME, 'password' => DB_PASSWORD, 'database' => DB_NAME);
}

$oauth = OAuthStore::instance('MySQL', get_db_options());

For Mysqli use below code to connect

$con = mysqli_connect("localhost","my_user","my_password","my_db");

OAuthStore::instance('MySQLi', array('conn' => $con, 'table_prefix' => UserConfig::$mysql_prefix));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM