背景:由于不想让用户查询到我的secretKey和accesskey,所以想在后端做一个临时url生成接口。
问题:在使用临时url上传文件到华为云obs的时候遇到403 forbidden问题,在浏览器开发者模式的网络请求记录里面还看不到返回响应里面的具体报错信息,需要双击网络请求,再访问一次才能看到一个xml的报错信息,具体报错信息是:
The request signature we calculated does not match the signature you provided. Check your key and signing method
分析:后来在createTemporarySignature方法的源码中看到,在签名的计算中不仅用到了url、时间、还有其头相关信息:
StringBuilder canonicalRequest = (new StringBuilder(requestMethod)).append("\n").append((CharSequence)(canonicalUri.length() == 0 ? "/" : canonicalUri)).append("\n").append(canonicalQueryString).append("\n").append(canonicalHeaders).append("\n").append(signedHeaders).append("\n").append("UNSIGNED-PAYLOAD");
StringBuilder stringToSign = (new StringBuilder("AWS4-HMAC-SHA256")).append("\n").append(longDate).append("\n").append(shortDate).append("/").append("region").append("/").append("s3").append("/").append("aws4_request").append("\n").append(V4Authentication.byteToHex(V4Authentication.sha256encode(canonicalRequest.toString())));
signedUrl.append("&").append("X-Amz-").append("Signature=").append(V4Authentication.caculateSignature(stringToSign.toString(), shortDate, securityKey.getSecretKey()));
TemporarySignatureResponse response = new TemporarySignatureResponse(signedUrl.toString());
这时候就想到了,我为了做临时url能否访问的测试,在生成临时url时候,content-type:写死的image/png,而我实际上传文是image/jpeg,因此就发现了问题,把content-type统一,上传成功!