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


How can I test if I have all the right credentials with php-opencloud sdk?

这是我现在的代码:

$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->导入凭据($array_creds); ?

我正在徘徊,因为如果我不需要,我不想写入数据库。

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

这似乎是维护持久会话的好策略,因为您正在重用现有的令牌 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() - 因此这意味着您无需自己调用它。但是对于您当前的版本,值得将其保留。

这能回答一切吗?