存储在mysql数据库中的Oauth令牌不起作用,但在使用会话时可以正常运行

时间:2019-01-12 11:53:48

标签: php mysql oauth

我正在尝试使用4shared API创建应用程序,但是要使用它,我需要使用Oauth在4shared中进行授权。问题是,当我使用会话存储oauth_token时,一切正常,但是当我试图在Mysql数据库中存储令牌时,我得到了错误:

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
}

我已经创建了正确的mysql数据库,并将mysql.sql文件从Oauth的store文件夹导入到其中。另外,如果我不使用“ conn”作为选项,则它根本不会连接到数据库,但是我可以使用“ conn”选项连接到数据库。

这是我的代码:

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);

}

OAuthStore::instance("MySQLi", $options);更改为OAuthStore::instance("sessions", $options);时,一切正常

根据评论者的要求: MySQL版本: 适用于Linux(x86_64)的mysql Ver 14.14 Distrib 5.7.19,使用EditLine包装器

my.cnf内容(我在同一台服务器上还有许多其他数据库,但这些数据库运行正常,因此应该不会有问题)

[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

我还使用创建数据库的方式链接到文件(这是oauth提供的文件): https://pastebin.com/2eb0aTbL

1 个答案:

答案 0 :(得分:-1)

嗨,我认为您没有正确创建实例。

您能否在下面的链接中查看Oauth实例创建的各种示例?

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());

对于Mysqli,请使用以下代码进行连接

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

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