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

  • 回答 (3)
  • 关注 (1)
  • 查看 (2208)

使用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);

用户1081258用户1081258提问于
Jinqn

腾讯 · 高级工程师 (已认证)

腾讯云COS前端开发修改于
推荐

nodejs 拿到了 pathname 之后,加一个 decodeURIComponent 就好了

是 sdk 这里处理兼容问题

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

sdk 里的 server/auth.js 已更新

用户1139461回答于

请问下,这个问题你最后解决了吗?我看了上面的回答,对照了下我auth.js里面的代码,已经是最新的了:

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

但是还是得到了和你一样的错误

用户1081258回答于

请问有人使用过javascript SDK吗,跟踪SDK,很多地方的APPID为undefined,但是在new COS已经设置了,不需要每次都设置吧,是不是逻辑有问题?

跨域访问CORS严格按照文档设置,只有origin=http://192.168.1.1:8100不一致,有没有可能是此处有问题?

所属标签

可能回答问题的人

  • 云存储小天使

    腾讯云 · 云存储 (已认证)

    16 粉丝0 提问0 回答
  • galenye

    腾讯 · 工程师 (已认证)

    5 粉丝0 提问37 回答
  • Jinqn

    腾讯 · 高级工程师 (已认证)

    16 粉丝0 提问59 回答
  • 腾讯云技术服务团队

    腾讯云 · 技术服务团队 (已认证)

    25 粉丝0 提问3 回答
  • 宝哥@devops运维

    腾讯 · 高级云计算工程师 (已认证)

    68 粉丝0 提问0 回答
  • elliswu

    腾讯计算机系统有限公司 · 高级工程师 (已认证)

    4 粉丝0 提问0 回答

扫码关注云+社区

领取腾讯云代金券