参考
如何使用STS以及签名URL临时授权访问OSS资源(PHP)_对象存储(OSS)-阿里云帮助中心
目的
官方sdk并没有授权目录,而很多时候需要授权目录,比如hls文件夹授权,总不能几千个切片全部跑一遍授权
主要实现oss地址+Expires+OSSAccessKeyId+security-token+Signature自行拼接成授权访问地址,只需.无需new
代码
获取security-token
参考上面官方地址,下述中tk包含获取security-token结果返回的accessKeyId,accessKeySecret,securityToken
获取签名
Oss.php
public static function getSignature($tk,$endpoint,$bucket,$object,$timeout,$method="GET",$options=array())
{
$accessKeyId = $tk['accessKeyId'];
$accessKeySecret = $tk['accessKeySecret'];
$securityToken = $tk['securityToken'];
$timeout = time()+$timeout;
$stringToSign=$method."\n\n\n".$timeout."\n".'/'.$bucket.'/'.$object.'?security-token='.$securityToken;
$signature=base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret, true));
$query = [
'security-token'=>$securityToken,
'OSSAccessKeyId'=>$accessKeyId,
'Expires'=>strval($timeout),
'Signature'=>$signature,
];
$queryString=self::toQueryString($query);
$pp = parse_url($endpoint);
$parsed_url=[
'scheme'=>$pp['scheme'],
'host'=>$bucket.'.'.$pp['host'],
'path'=>'/'.$object,
'query'=>$queryString,
];
$url = self::unparseUrl($parsed_url);
return $url;
}
private static function toQueryString($options = array())
{
$temp = array();
uksort($options, 'strnatcasecmp');
foreach ($options as $key => $value) {
if (is_string($key) && !is_array($value)) {
if (strlen($value) > 0) {
$temp[] = rawurlencode($key) . '=' . rawurlencode($value);
} else {
$temp[] = rawurlencode($key);
}
}
}
return implode('&', $temp);
}
private static function unparseUrl($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
return "$scheme$host$port$path$query";
}
调用
$oss = new Oss($id);
// $oss->getTK();
$endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
$bucket= "b999a7c3bcc5535b4c8e277e18b7b6e1";
$tk = unserialize(file_get_contents('tk'));
$object=$oss_list_file;
$timeout=3000;
$method = "GET";
$options=array();
$link = $oss::getSignature($tk,$endpoint,$bucket,$object,$timeout,$method,$options);
echo $link;
结语
为什么官方文档没有类似说明?也许是大有大的难处吧!累死本小白了!!