如何使用php-opencloud sdk测试我是否拥有所有正确的凭据?

时间:2013-09-05 16:50:54

标签: php api rackspace-cloud rackspace

以下是我的代码:

$cloud = new Rackspace('https://identity.api.rackspacecloud.com/v2.0/', $php_cloudconfig['credentials']);
$array_creds = getCredentials();
$cloud->ImportCredentials($array_creds);

$array_creds = $cloud->ExportCredentials();
setCredentials($array_creds['authorization_token'], $array_creds['expiration'], $array_creds['tenant_id'], $array_creds['service_catalog']);

function getCredentials() {
    $sql_get_credential = "SELECT * FROM cloud_apiconnection";
    $q = $conn->prepare($sql_get_credential);
    return $q->execute();
}

function setCredentials($authorization_token, $expiration, $tenant_id, $service_catalog)     {
    $sql_insert = "INSERT INTO cloud_apiconnection (authorization_token, expiration, tenant_id, service_catalog) VALUES (:authorization_token, :expiration, :tenant_id, :service_catalog)";
    $q = $conn->prepare($sql_insert);
    $q->execute(array(':authorization_token' => $authorization_token, ':expiration' => $expiration, ':tenant_id' => $tenant_id, ':service_catalog' => $service_catalog));
}

有没有办法检测凭据是否已更新:$ cloud-> ImportCredentials($ array_creds); ?

我在游荡,因为如果我不需要,我不想写入数据库。

这也是管理我与RackSpace API连接的最佳策略吗?

1 个答案:

答案 0 :(得分:2)

这似乎是维护持久会话的好策略,因为您重新使用现有的令牌ID。唯一的其他建议是将您的凭据缓存在本地文件中,而不是进行MySQL事务。您并不需要存储租户ID和服务目录,因为这些都可以通过软件层轻松检索。

要检查现有令牌的有效性,请执行以下操作:

$connection = new Rackspace(...);

// Import existing credentials
$credentials = getCredentials();
$connection->importCredentials($credentials);

// Authenticate against the API to make sure your token is still valid
$connection->authenticate();

// Compare result
$newCredentials = $connection->exportCredentials();

if ($newCredentials['authorization_token'] != $credentials['authorization_token']) {
   // You know it's been updated, so save new ones
   setCredentials();
}

所有authenticate()方法都是针对Rackspace API执行请求;并根据结果,它有效地告诉您现有的东西是否仍然有效。当其他方法调用authenticate()时,它们通常会事先进行另一次检查:它们检查到期值(即不是过去)。您可以实现他们所做的相同的事情(以确定是否需要刷新和保存凭据):

if (time() > ($credentials['expiration'] - RAXSDK_FUDGE)) {
   // They're old, you need to call authenticate()
} else {
   // They seem to be still valid. Sweet!
}

顺便说一下,我们最近更改了此功能,以便exportCredentials()拨打authenticate() - 这意味着您不需要自己调用它。但是对于你当前的版本,它值得留下它。

这会回答一切吗?