Skip to content

Commit

Permalink
update demo
Browse files Browse the repository at this point in the history
  • Loading branch information
carsonxu committed Sep 11, 2018
1 parent 3d2ad98 commit e9fd341
Show file tree
Hide file tree
Showing 6 changed files with 256 additions and 44 deletions.
2 changes: 1 addition & 1 deletion csp/csp.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ <h1>cos-js-sdk-v5</h1>
ForcePathStyle: true, // 后缀式
// Domain: 'http://{Bucket}.cos.{Region}.example.com', // 前缀式
getAuthorization: function (options, callback) {
var url = '../server/sts.php';
var url = './sts.php';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
Expand Down
168 changes: 168 additions & 0 deletions csp/sts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
<?php
// 临时密钥计算样例

// 配置参数
$config = array(
'Url' => 'http://sts.api2.example.com/v2/index.php',
'Domain' => 'sts.api2.example.com',
'Proxy' => '',
'SecretId' => 'AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 固定密钥
'SecretKey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 固定密钥
'Bucket' => 'test-1250000000',
'Region' => 'default',
'AllowPrefix' => '_ALLOW_DIR_/*', // 必填,这里改成允许的路径前缀,这里可以根据自己网站的用户登录态判断允许上传的目录,例子:* 或者 a/* 或者 a.jpg
);

// obj 转 query string
function json2str($obj) {
ksort($obj);
$arr = array();
foreach ($obj as $key => $val) {
array_push($arr, $key . '=' . $val);
}
return join('&', $arr);
}

// 计算临时密钥用的签名
function getSignature($opt, $key, $method) {
global $config;
$formatString = $method . $config['Domain'] . '/v2/index.php?' . json2str($opt);
$formatString = urldecode($formatString);
$sign = hash_hmac('sha1', $formatString, $key);
$sign = base64_encode(hex2bin($sign));
return $sign;
}

// 计算临时密钥用的签名
function resourceUrlEncode($str) {
$str = rawurlencode($str);
//特殊处理字符 !()~
$str = str_replace('%2F', '/', $str);
$str = str_replace('%2A', '*', $str);
$str = str_replace('%21', '!', $str);
$str = str_replace('%28', '(', $str);
$str = str_replace('%29', ')', $str);
$str = str_replace('%7E', '~', $str);
return $str;
}

// 获取临时密钥
function getTempKeys() {

global $config;

// 判断是否修改了 AllowPrefix
if ($config['AllowPrefix'] === '_ALLOW_DIR_/*') {
return array('error'=> '请修改 AllowPrefix 配置项,指定允许上传的路径前缀');
}

$ShortBucketName = substr($config['Bucket'],0, strripos($config['Bucket'], '-'));
$AppId = substr($config['Bucket'], 1 + strripos($config['Bucket'], '-'));
$policy = array(
'version'=> '2.0',
'statement'=> array(
array(
'action'=> array(
// // 这里可以从临时密钥的权限上控制前端允许的操作
// 'name/cos:*', // 这样写可以包含下面所有权限

// // 列出所有允许的操作
// // ACL 读写
// 'name/cos:GetBucketACL',
// 'name/cos:PutBucketACL',
// 'name/cos:GetObjectACL',
// 'name/cos:PutObjectACL',
// // 简单 Bucket 操作
// 'name/cos:PutBucket',
// 'name/cos:HeadBucket',
// 'name/cos:GetBucket',
// 'name/cos:DeleteBucket',
// 'name/cos:GetBucketLocation',
// // Versioning
// 'name/cos:PutBucketVersioning',
// 'name/cos:GetBucketVersioning',
// // CORS
// 'name/cos:PutBucketCORS',
// 'name/cos:GetBucketCORS',
// 'name/cos:DeleteBucketCORS',
// // Lifecycle
// 'name/cos:PutBucketLifecycle',
// 'name/cos:GetBucketLifecycle',
// 'name/cos:DeleteBucketLifecycle',
// // Replication
// 'name/cos:PutBucketReplication',
// 'name/cos:GetBucketReplication',
// 'name/cos:DeleteBucketReplication',
// // 删除文件
// 'name/cos:DeleteMultipleObject',
// 'name/cos:DeleteObject',
// 简单文件操作
'name/cos:PutObject',
'name/cos:PostObject',
'name/cos:AppendObject',
'name/cos:GetObject',
'name/cos:HeadObject',
'name/cos:OptionsObject',
'name/cos:PutObjectCopy',
'name/cos:PostObjectRestore',
// 分片上传操作
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload',
'name/cos:AbortMultipartUpload',
),
'effect'=> 'allow',
'principal'=> array('qcs'=> array('*')),
'resource'=> array(
'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/',
'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/' . resourceUrlEncode($config['AllowPrefix'])
)
)
)
);

$policyStr = str_replace('\\/', '/', json_encode($policy));
$Action = 'GetFederationToken';
$Nonce = rand(10000, 20000);
$Timestamp = time() - 1;
$Method = 'GET';

$params = array(
'Action'=> $Action,
'Nonce'=> $Nonce,
'Region'=> '',
'SecretId'=> $config['SecretId'],
'Timestamp'=> $Timestamp,
'durationSeconds'=> 7200,
'name'=> 'cos',
'policy'=> urlencode($policyStr)
);
$params['Signature'] = urlencode(getSignature($params, $config['SecretKey'], $Method));

$url = $config['Url'] . '?' . json2str($params);
$ch = curl_init($url);
$config['Proxy'] && curl_setopt($ch, CURLOPT_PROXY, $config['Proxy']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if(curl_errno($ch)) $result = curl_error($ch);
curl_close($ch);

$result = json_decode($result, 1);
if (isset($result['data'])) $result = $result['data'];

return $result;
};

// 获取临时密钥,计算签名
$tempKeys = getTempKeys();

// 返回数据给前端
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://127.0.0.1'); // 这里修改允许跨域访问的网站
header('Access-Control-Allow-Headers: origin,accept,content-type');
echo json_encode($tempKeys);
20 changes: 16 additions & 4 deletions server/sts-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,24 @@ var util = {
// 计算签名
getSignature: function (opt, key, method) {
var formatString = method + config.Domain + '/v2/index.php?' + util.json2str(opt);
formatString = decodeURIComponent(formatString);
var hmac = crypto.createHmac('sha1', key);
var sign = hmac.update(new Buffer(formatString, 'utf8')).digest('base64');
return sign;
},
};

// 计算临时密钥用的签名
function resourceUrlEncode(str) {
str = encodeURIComponent(str);
//特殊处理字符 !()~
str = str.replace(/%2F/g, '/');
str = str.replace(/%2A/g, '*');
str = str.replace(/%28/g, '(');
str = str.replace(/%29/g, ')');
return str;
}

// 拼接获取临时密钥的参数
var getTempKeys = function (callback) {

Expand All @@ -62,7 +74,7 @@ var getTempKeys = function (callback) {
'version': '2.0',
'statement': [{
'action': [
// 这里可以从临时密钥的权限上控制前端允许的操作
// // 这里可以从临时密钥的权限上控制前端允许的操作
// 'name/cos:*', // 这样写可以包含下面所有权限

// // 列出所有允许的操作
Expand Down Expand Up @@ -116,7 +128,7 @@ var getTempKeys = function (callback) {
'principal': {'qcs': ['*']},
'resource': [
'qcs::cos:' + config.Region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/',
'qcs::cos:' + config.Region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + config.AllowPrefix
'qcs::cos:' + config.Region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + resourceUrlEncode(config.AllowPrefix)
]
}]
};
Expand All @@ -141,8 +153,8 @@ var getTempKeys = function (callback) {
SecretId: config.SecretId,
Timestamp: Timestamp,
durationSeconds: 7200,
name: '',
policy: policyStr,
name: 'cos',
policy: encodeURIComponent(policyStr),
};
params.Signature = encodeURIComponent(util.getSignature(params, config.SecretKey, Method));

Expand Down
34 changes: 20 additions & 14 deletions server/sts-auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,25 @@ function json2str($obj) {
function getSignature($opt, $key, $method) {
global $config;
$formatString = $method . $config['Domain'] . '/v2/index.php?' . json2str($opt);
$formatString = urldecode($formatString);
$sign = hash_hmac('sha1', $formatString, $key);
$sign = base64_encode(hex2bin($sign));
return $sign;
}

// 计算临时密钥用的签名
function resourceUrlEncode($str) {
$str = rawurlencode($str);
//特殊处理字符 !()~
$str = str_replace('%2F', '/', $str);
$str = str_replace('%2A', '*', $str);
$str = str_replace('%21', '!', $str);
$str = str_replace('%28', '(', $str);
$str = str_replace('%29', ')', $str);
$str = str_replace('%7E', '~', $str);
return $str;
}

// 获取临时密钥
function getTempKeys() {

Expand All @@ -59,7 +73,7 @@ function getTempKeys() {
array(
'action'=> array(
// // 这里可以从临时密钥的权限上控制前端允许的操作
// 'name/cos:*', // 这样写可以包含下面所有权限
// 'name/cos:*', // 这样写可以包含下面所有权限

// // 列出所有允许的操作
// // ACL 读写
Expand Down Expand Up @@ -112,20 +126,13 @@ function getTempKeys() {
'principal'=> array('qcs'=> array('*')),
'resource'=> array(
'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/',
'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/' . $config['AllowPrefix']
'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/' . resourceUrlEncode($config['AllowPrefix'])
)
)
)
);

$policyStr = str_replace('\\/', '/', json_encode($policy));

// 有效时间小于 30 秒就重新获取临时密钥,否则使用缓存的临时密钥
if (isset($_SESSION['tempKeysCache']) && isset($_SESSION['tempKeysCache']['expiredTime']) && isset($_SESSION['tempKeysCache']['policyStr']) &&
$_SESSION['tempKeysCache']['expiredTime'] - time() > 30 && $_SESSION['tempKeysCache']['policyStr'] === $policyStr) {
return $_SESSION['tempKeysCache'];
}

$Action = 'GetFederationToken';
$Nonce = rand(10000, 20000);
$Timestamp = time() - 1;
Expand All @@ -138,8 +145,8 @@ function getTempKeys() {
'SecretId'=> $config['SecretId'],
'Timestamp'=> $Timestamp,
'durationSeconds'=> 7200,
'name'=> '',
'policy'=> $policyStr
'name'=> 'cos',
'policy'=> urlencode($policyStr)
);
$params['Signature'] = urlencode(getSignature($params, $config['SecretKey'], $Method));

Expand All @@ -148,18 +155,17 @@ function getTempKeys() {
$config['Proxy'] && curl_setopt($ch, CURLOPT_PROXY, $config['Proxy']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if(curl_errno($ch)) $result = curl_error($ch);
curl_close($ch);

$result = json_decode($result, 1);
if (isset($result['data'])) $result = $result['data'];
$_SESSION['tempKeysCache'] = $result;
$_SESSION['tempKeysCache']['policyStr'] = $policyStr;

return $result;
};
}

// 计算 COS API 请求用的签名
function getAuthorization($keys, $method, $pathname)
Expand Down
Loading

0 comments on commit e9fd341

Please sign in to comment.