使用URL签名授权访问
通过生成签名URL的形式提供给用户一个临时的访问URL。在生成URL时,您可以指定URL过期的时间,从而限制用户长时间访问。
提示:
- 以下场景的完整代码请参考:GitHub
<?php
/**
* 生成GetObject的签名url,主要用于私有权限下的读访问控制
*
* @param $ossClient OssClient OSSClient实例
* @param $bucket string bucket名称
* @return null
*/
function getSignedUrlForGettingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600; // URL的有效期是3600秒
try{
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl. "\n");
/**
* 可以类似的代码来访问签名的URL,也可以输入到浏览器中去访问
*/
$request = new RequestCore($signedUrl);
$request->set_method('GET');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
提示:
- 生成的URL默认以GET方式访问,这样,用户可以直接通过浏览器访问相关内容。
<?php
/**
* 生成PutObject的签名url,主要用于私有权限下的写访问控制
*
* @param OssClient $ossClient OSSClient实例
* @param string $bucket bucket名称
* @return null
* @throws OssException
*/
function getSignedUrlForPuttingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
$options = NULL;
try{
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT");
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl. "\n");
$content = file_get_contents(__FILE__);
$request = new RequestCore($signedUrl);
$request->set_method('PUT');
$request->add_header('Content-Type', '');
$request->add_header('Content-Length', strlen($content));
$request->set_body($content);
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
<?php
$accessKeyId = "<accessKeyId>";
$accessKeySecret = "<accessKeySecret>";
$securityToken = "<securityToken>";
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。