Coder Social home page Coder Social logo

qcloud-cos-sts-sdk's Introduction

QCloud COS 服务临时密钥 SDK

本 SDK 可以帮助您在后台快速搭建一个临时密钥服务,用于访问腾讯云 COS 下的资源。

访问管理

腾讯云 COS 服务在使用时需要对请求进行访问管理。通过临时密钥机制,您可以临时授权您的 App 访问您的存储资源,而不会泄露您的永久密钥。密钥的有效期由您指定,过期后自动失效。**通常,我们都不建议您把永久密钥放到客户端代码中。**本文主要介绍如何在后台快速搭建一个临时密钥服务,通过生成的临时密钥来对上传或者下载请求进行签名,从而保证您数据的安全性。

架构

整体架构图如下所示:

cos接入cam框架图

其中:

  • 应用 APP:即用户手机上的 App。

  • COS:腾讯云对象存储,负责存储 App 上传的数据。

  • CAM:腾讯云访问管理,用于生成 COS 的临时密钥。

  • 应用服务器:用户自己的后台服务器,这里用于获取临时密钥,并返回给应用 App。

获取永久密钥

临时密钥需要通过永久密钥才能生成。请登录 腾讯云访问管理控制台 获取,包含:

  • SecretId
  • SecretKey

如何快速搭建临时密钥服务

集成 SDK 到 您的后台服务

如果您已经有独立的后台服务,我们建议您直接集成我们提供的 SDK 到现在的后台服务中。

第一步:集成服务器 SDK

目前我们提供了以下语言的 SDK,帮忙您快速在后台集成生成密钥的功能,您可以根据自己后台的架构自行选择:

  • Java
  • Node.js
  • PHP
  • Python
  • Go
  • .NET

第二步:发布 Web API

将您的服务以 Web API 的方式发布出去,这样您授权的客户端 App,如 Android、iOS,Web端,都可以通过标准的 HTTP 协议请求到临时密钥,访问 COS 服务。

高级功能

您可以通过 Scope 的方式更细粒度的控制返回密钥的权限,详细请看 细粒度控制权限

其他语言

如果您需要其他语言的 SDK,可以参考社区提供的版本。

语言 作者 仓库
elixir @scottming scottming/qcloud_cos_sts

qcloud-cos-sts-sdk's People

Contributors

agin719 avatar astro2049 avatar bradyxiao avatar brandozhang avatar bug-is-zhanglinlin avatar carsonxu avatar dt3310321 avatar dzkol avatar fysntian avatar konakonall avatar l-iberty avatar learningzhang avatar lewzylu avatar liuyongqing avatar livehigh avatar losingle avatar techird avatar tuuna avatar zephyr2222 avatar zhy1985555 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

qcloud-cos-sts-sdk's Issues

急需 go sdk

找了一圈居然没有 Go 的 SDK。。。急需啊 please help!

腾讯的接口没有全局架构

腾讯的接口都是不同团队各自为政,一个cos接口搞出两套,咱就不能全局统筹整合一下吗?微信的接口也是,有的是xml格式,有的是json格式,我服了u。cos抄袭了七牛云,不过咱api是否也能抄下七牛云呢,七牛api是真心好用。
<groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId>
<groupId>com.tencent.cloud</groupId> <artifactId>cos-sts-java</artifactId>

go版本SDK接口返回报错

直接使用go里面的demo去创建token的

Code: InvalidParameter.GrantOtherResource, Message: [QC_STS] cant grant other resource, RequestId

代码

	opt := &sts.CredentialOptions{
		DurationSeconds: expiredAt,
		Region:          region,
		Policy: &sts.CredentialPolicy{
			Statement: []sts.CredentialPolicyStatement{
				{
					Action: []string{
						"name/cos:PostObject",
						"name/cos:PutObject",
					},
					Effect: "allow",
					Resource: []string{
                                                  // 这里的uid是腾讯云后台的APPID?
						"qcs::cos:" + region + ":uid/" + uid + ":" + bucket + "/tmp",
					},
				},
			},
		},
	}

DotNet Framework 4.7.2获取临时令牌报错,非dotnet Core

错误信息:

TencentCloud.Common.TencentCloudSDKException:“code:InvalidParameter.GrantOtherResource message:[QC_STS] cant grant other resource ”

两次尝试都报此错误:
1.nuget: Tencent.QCloud.Cos.Sts.Sdk 3.0.1
2.直接github复制Master 的STSClient源码,放进源文件跑

测试过吗??

永远都是
Code: AuthFailure.SignatureFailure, Message: The provided credentials could not be validated. Please check your signature is correct.

StartTime 的解释

StartTime:文档上说是密钥的起止时间, 个人理解应该是起始时间吧.

java sdk 3.0.8报错

Exception in thread "main" java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set;
at com.tencent.cloud.CosStsClient.downCompat(CosStsClient.java:96)
at com.tencent.cloud.CosStsClient.getCredential(CosStsClient.java:63)

关于 sdk 选择的问题

除了这里的 sdk,还在 https://console.cloud.tencent.com/api/explorer?Product=ms&Version=2018-04-08&Action=CreateCosSecKeyInstance&SignVersion= 这里看到了获取云 COS 临时密钥的一个示例代码。代码如下:

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

import com.tencentcloudapi.ms.v20180408.MsClient;

import com.tencentcloudapi.ms.v20180408.models.CreateCosSecKeyInstanceRequest;
import com.tencentcloudapi.ms.v20180408.models.CreateCosSecKeyInstanceResponse;

public class CreateCosSecKeyInstance
{
    public static void main(String [] args) {
        try{

            Credential cred = new Credential("", "");
            
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ms.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);            
            
            MsClient client = new MsClient(cred, "", clientProfile);
            
            String params = "{}";
            CreateCosSecKeyInstanceRequest req = CreateCosSecKeyInstanceRequest.fromJsonString(params, CreateCosSecKeyInstanceRequest.class);
            
            CreateCosSecKeyInstanceResponse resp = client.CreateCosSecKeyInstance(req);
            
            System.out.println(CreateCosSecKeyInstanceRequest.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
        }

    }
    
}

想问一下,两种生成 COS 临时密钥的方式都是正确的吗?

我们服务器端当前代码使用的是上面示例代码的这种,然后前端计算 Authorization 上传文件总是返回 AccessDenied

获取临时KEY报签名错误

  • 环境
    PHP :7.2.4
    qcloud_sts/qcloud-sts-sdk:3.0.5

  • 代码

use QCloud\COSSTS\Sts;

class CosUploadController extends Controller
{

    /**
     * 获取 COS 临时KEY
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     *
     * @desc https://cloud.tencent.com/document/product/436/14048
     */
    public function tempKey()
    {
        $sts = new Sts();
        $config = [
            'url' => 'https://sts.tencentcloudapi.com/',
            'domain' => 'sts.tencentcloudapi.com',
            'proxy' => '',
            // 固定密钥
            'secretId' => config('cos.credentials.secretId'),
            // 固定密钥
            'secretKey' => config('cos.credentials.secretKey'),
            // 换成你的 bucket
            'bucket' => config('cos.credentials.bucket'),
            // 换成 bucket 所在园区
            'region' => config('cos.credentials.region'),
            // 密钥有效期
            'durationSeconds' => 1800,
            // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            'allowPrefix' => '*',
            // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => [
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ]
        ];

        $tempKeys = $sts->getTempKeys(array_filter($config));

        $tempKeys['bucket'] = config('cos.credentials.bucket');
        $tempKeys['region'] = config('cos.credentials.region');

        return $this->success($tempKeys);
    }
}
  • 响应内容
{
	"Error": {
		"Code": "AuthFailure.SignatureFailure",
		"Message": "The provided credentials could not be validated. Please check your signature is correct."
	},
	"RequestId": "af83286b-9c13-4c73-a62e-ba151b60ca5b"
}

soc-sts-java获取临时令牌失败

sdk使用3.0.8版本,参考官方Demo编写,日志报错如下

java.io.IOException: result = {"Response":{"Error":{"Code":"InvalidParameter.ResouceError","Message":"[QC_STS] resource error"},"RequestId":"90d7e639-4068-4735-8da3-beeef74cda27"}}
对比官网错误码描述,说是策略resource字段不合法。
然后我反复对照了官网针对resource的要求,完全符合规定啊,为何还是报错

sts_client_test.py request_sts()服务端报错

Hi,你好!测试python sdk 的demo中的sts_client_test.py request_sts()
服务端程序报错如下:
Exception: ("result: {u'RequestId': u'1167ba7c-f4e5-4b36-9bfe-80b3a64a86fa', u'Error': {u'Message': u'The provided credentials could not be validated. Please check your signature is correct.', u'Code': u'AuthFailure.SignatureFailure'}}", KeyError('ExpiredTime',))
服务端成secretkey和secretid都已换成自己申请的了。
request_sts2()是没有问题。服务器端修改方法和request_sts一致。
请问这是什么原因呢?

php获取临时密钥 AuthFailure.SignatureFailure

php 7.2.13

Fatal error: Uncaught Exception: {"Error":{"Code":"AuthFailure.SignatureFailure","Message":"The provided credentials could not be validated. Please check your signature is correct."},"RequestId":"9939e6a5-cc6e-41fe-a316-3fcf64771243"}

依照例程,只改了关键信息.

`<?php

require 'vendor/autoload.php';

use QCloud\COSSTS\Sts;

$sts = new Sts();
$config = array(
'url' => 'https://sts.tencentcloudapi.com/',
'domain' => 'sts.tencentcloudapi.com',
'proxy' => '',
'secretId' => getenv('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'), // 固定密钥
'secretKey' => getenv('xxxxxxxxxxxxxxxxxxxxxxxx'), // 固定密钥
'bucket' => 'xxxxxxxxxxxxxxxxx-1252375781', // 换成你的 bucket
'region' => 'ap-nanjing', // 换成 bucket 所在园区
'durationSeconds' => 1800, // 密钥有效期
'allowPrefix' => '*',
'allowActions' => array (
// 简单上传
'name/cos:PutObject',
'name/cos:PostObject',
// 分片上传
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload'
)
);
// 获取临时密钥,计算签名
$tempKeys = $sts->getTempKeys($config);
echo json_encode($tempKeys);`

A non-numeric value encountered

我使用PHP版本为:PHP 7.3.11
当获取调用临时上传key时,出现A non-numeric value encountered 错误。需要将 sts.php 源码的 130行 ”$result = "error: " . + $e->getMessage();“ 中的加号去掉

SDK设计问题

Go语言SDK的Resource能解释一下吗?为什么别的语言版本都是allowPrefix,唯独Go语言不一样,而且还需要个appid?别的都不用的,能解释一下这个问题吗

dotnet 版SDK报资源错误

STSClient.cs文件中,在getPolicy 有一段代码:
foreach (string action in allowActions) {
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("action", action);
dic.Add("effect", "allow");

            string[] splitParts = bucket.Split('-');
            string appId = splitParts[splitParts.Length - 1];
            string bucketName = bucket.Substring(0, bucket.Length - appId.Length - 1);
            if (!allowPrefix.StartsWith("/")) {
                allowPrefix = "/" + allowPrefix;
            }
            dic.Add("resource", string.Format("qcs::cos:{0}:uid/{1}:{2}{3}",
                region, appId, bucketName, allowPrefix));
            states.Add(dic);
        }

bucketName 是截取掉ID之后的存储桶名称,测试生成凭证的时候会报错,实际上需要用到完整的存储桶名称,把代码
dic.Add("resource", string.Format("qcs::cos:{0}:uid/{1}:{2}{3}",
region, appId, bucketName, allowPrefix));
替换成:
dic.Add("resource", string.Format("qcs::cos:{0}:uid/{1}:{2}{3}",
region, appId, bucket, allowPrefix));
最后成功获取临时凭证。

是否支持.net framework 4.0及以下版本?

nuget-error

我们项目是.net framework 4.0版本,无法正常引入cos sdk。
web前端直传资源到腾讯云,需要后端产生临时credential,现在cos的sdk都无法正常引入。
请问有.net framework 4.0及以下版本的sdk吗?

哎 这什么文档啊 简直服了

durationSeconds这个东西设置了一点用没有,?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

文档里写的getPolicy使用例子问题

实测getPolicy必须带bucket和region,但是带了那2属性出来的权限再计算出的临时授权给到前端,所有的接口都是403!
所以最好的办法就是别用getPolicy构造授权权限结构,自己手写!!!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.