首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >COS javascript SDK 测试始终报错403,请各位帮忙看一下,是什么问题?

COS javascript SDK 测试始终报错403,请各位帮忙看一下,是什么问题?

提问于 2017-11-12 14:47:13
回答 3关注 1查看 4.2K

使用https://cloud.tencent.com/document/product/436/11459的例子,测试始终报403错误。

1 已确认http://127.0.0.1:3000/auth可以正确响应

信息如下:

一、

response:

<?xml version='1.0' encoding='utf-8' ?>

<Error>

<Code>SignatureDoesNotMatch</Code>

<Message>The Signature you specified is invalid.</Message>

<Resource>*******-**********.cos.ap-chengdu.myqcloud.com</Resource>

<RequestId>NWEwN2ViYTlfMjZiMjU4NjRfODAyYV81YmNlZQ==</RequestId>

<TraceId>OGVmYzZiMmQzYjA2OWNhODk0NTRkMTBiOWVmMDAxODc0OWRkZjk0ZDM1NmI1M2E2MTRlY2MzZDhmNmI5MWI1OTBjYzE2MjAxN2M1MzJiOTdkZjMxMDVlYTZjN2FiMmI0NTI4MjA5OWExOTcxZGExNmE2MDYxNGJlZTgzY2RiNjA=</TraceId>

</Error>

二、

request:

Request URL:http://*******-******.cos.ap-chengdu.myqcloud.com/?uploads&prefix=cors.png

Request Method:GET

Status Code:403 Forbidden

Remote Address:127.0.0.1:1080

Referrer Policy:no-referrer-when-downgrade

Response Headers

view source

Access-Control-Allow-Headers:

Access-Control-Allow-Methods:PUT,GET,POST,DELETE,HEAD

Access-Control-Allow-Origin:http://192.168.1.160:8100

Access-Control-Expose-Headers:ETag

Access-Control-Max-Age:5

Connection:keep-alive

Content-Length:480

Content-Type:application/xml

Date:Sun, 12 Nov 2017 06:35:21 GMT

Server:tencent-cos

x-cos-request-id:NWEwN2ViYTlfMjZiMjU4NjRfODAyYV81YmNlZQ==

x-cos-trace-id:OGVmYzZiMmQzYjA2OWNhODk0NTRkMTBiOWVmMDAxODc0OWRkZjk0ZDM1NmI1M2E2MTRlY2MzZDhmNmI5MWI1OTBjYzE2MjAxN2M1MzJiOTdkZjMxMDVlYTZjN2FiMmI0NTI4MjA5OWExOTcxZGExNmE2MDYxNGJlZTgzY2RiNjA=

Request Headers

view source

Accept:*/*

Accept-Encoding:gzip, deflate

Accept-Language:en-US,en;q=0.9

Authorization:q-sign-algorithm=sha1&q-ak=**************************************&q-sign-time=1510468212;1510468812&q-key-time=1510468212;1510468812&q-header-list=&q-url-param-list=&q-signature=9dbc6907a84f8bdbb13e744a3ee159ff769dc510

Connection:keep-alive

DNT:1

Host:elearn-1255407726.cos.ap-chengdu.myqcloud.com

Origin:http://192.168.1.160:8100

Referer:http://192.168.1.160:8100/

User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36

Query String Parameters

view source

view URL encoded

uploads:

prefix:cors.png

三、

test.html 仅修改Bucket ,Region ,增加了对jquery.js的引用

<input id="file-selector" type="file">

<script src="../dist/jquery-2.2.2.min.js"></script>// ++++++++++++++++++++++++++++++++++修改语句

<script src="../dist/cos-js-sdk-v5.js"></script>

<script>

var Bucket = '******';// ++++++++++++++++++++++++++++++++++修改语句

var Region = '******';// ++++++++++++++++++++++++++++++++++修改语句

// 初始化实例

var cos = new COS({

AppId: **********,

getAuthorization: function (options, callback) {

// 异步获取签名

$.get('http://127.0.0.1:3000/auth', { // ++++++++++++++++++++++++++

+++++++修改语句

method: (options.Method || 'get').toLowerCase(),

pathname: '/' + (options.Key || '')

}, function (authorization) {

callback(authorization);

}, 'text');

}

});

// 监听选文件

document.getElementById('file-selector').onchange = function () {

var file = this.files[0];

if (!file) return;

// 分片上传文件

cos.sliceUploadFile({

Bucket: Bucket,

Region: Region,

Key: file.name,

Body: file,

}, function (err, data) {

console.log(err, data);

});

};

</script>

四、

auth,js 仅修改SecretId 和SecretKey

/**

* nodejs 签名样例

* 命令行启动服务: node auth.js

* 浏览器访问: http://127.0.0.1:3333

*/

var http = require('http');

var crypto = require('crypto');

var SecretId = '*******************************************'; // ++++++++++++++++++++++++++++++++++修改语句

var SecretKey = '******************************************';// ++++++++++++++++++++++++++++++++++修改语句

function camSafeUrlEncode(str) {

return encodeURIComponent(str)

.replace(/!/g, '%21')

.replace(/'/g, '%27')

.replace(/\(/g, '%28')

.replace(/\)/g, '%29')

.replace(/\*/g, '%2A');

}

function getAuthorization (method, pathname) {

var queryParams = {};

var headers = {};

method = (method ? method : 'get').toLowerCase();

pathname = pathname ? pathname : '/';

pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);

// 工具方法

var getObjectKeys = function (obj) {

var list = [];

for (var key in obj) {

if (obj.hasOwnProperty(key)) {

list.push(key);

}

}

return list.sort();

};

var obj2str = function (obj) {

var i, key, val;

var list = [];

var keyList = getObjectKeys(obj);

for (i = 0; i < keyList.length; i++) {

key = keyList[i];

val = obj[key] || '';

key = key.toLowerCase();

list.push(camSafeUrlEncode(key) + '=' + camSafeUrlEncode(val));

}

return list.join('&');

};

// 签名有效起止时间

var now = parseInt(new Date().getTime() / 1000) - 1;

var expired = now + 600; // 签名过期时刻,600 秒后

// 要用到的 Authorization 参数列表

var qSignAlgorithm = 'sha1';

var qAk = SecretId;

var qSignTime = now + ';' + expired;

var qKeyTime = now + ';' + expired;

var qHeaderList = getObjectKeys(headers).join(';').toLowerCase();

var qUrlParamList = getObjectKeys(queryParams).join(';').toLowerCase();

// 签名算法说明文档:https://www.qcloud.com/document/product/436/7778

// 步骤一:计算 SignKey

var signKey = crypto.createHmac('sha1', SecretKey).update(qKeyTime).digest('hex');

// 步骤二:构成 FormatString

var formatString = [method.toLowerCase(), pathname, obj2str(queryParams), obj2str(headers), ''].join('\n');

// 步骤三:计算 StringToSign

var stringToSign = ['sha1', qSignTime, crypto.createHash('sha1').update(formatString).digest('hex'), ''].join('\n');

// 步骤四:计算 Signature

var qSignature = crypto.createHmac('sha1', signKey).update(stringToSign).digest('hex');

// 步骤五:构造 Authorization

var authorization = [

'q-sign-algorithm=' + qSignAlgorithm,

'q-ak=' + qAk,

'q-sign-time=' + qSignTime,

'q-key-time=' + qKeyTime,

'q-header-list=' + qHeaderList,

'q-url-param-list=' + qUrlParamList,

'q-signature=' + qSignature

].join('&');

return authorization;

};

function getParam(url, name) {

var query, params = {}, index = url.indexOf('?');

if (index >= 0) {

query = url.substr(index + 1).split('&');

query.forEach(function (v) {

var arr = v.split('=');

params[arr[0]] = arr[1];

});

}

return params[name];

}

http.createServer(function(req, res){

if (req.url.substr(0, '/auth?'.indexOf('?')) === '/auth') {

var method = getParam(req.url, 'method');

var pathname = getParam(req.url, 'pathname');

var auth = getAuthorization(method, pathname);

console.log(method, pathname);

res.writeHead(200, {

'Content-Type': 'text/plain',

'Access-Control-Allow-Origin': '*',

'Access-Control-Allow-Methods': 'OPTIONS,GET,POST',

'Access-Control-Allow-Headers': 'accept,content-type',

'Access-Control-Max-Age': 60

});

res.write(auth || '');

res.end();

} else {

res.writeHead(404, {'Content-Type': 'text/html'});

res.write('404 Not Found');

res.end();

}

}).listen(3000);

相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档