/// 获取预签名下载链接
        public void GetPresignDownloadUrl()
        {
            //.cssg-snippet-body-start:[get-presign-download-url]
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid              = "1250000000";               //腾讯云账号 APPID
                preSignatureStruct.region             = "COS_REGION";               //存储桶地域
                preSignatureStruct.bucket             = "examplebucket-1250000000"; //存储桶
                preSignatureStruct.key                = "exampleobject";            //对象键
                preSignatureStruct.httpMethod         = "GET";                      //HTTP 请求方法
                preSignatureStruct.isHttps            = true;                       //生成 HTTPS 请求 URL
                preSignatureStruct.signDurationSecond = 600;                        //请求签名时间为600s
                preSignatureStruct.headers            = null;                       //签名中需要校验的 header
                preSignatureStruct.queryParameters    = null;                       //签名中需要校验的 URL 中请求参数

                string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct);

                //下载请求预签名 URL (使用永久密钥方式计算的签名 URL)
                string           localDir      = System.IO.Path.GetTempPath(); //本地文件夹
                string           localFileName = "my-local-temp-file";         //指定本地保存的文件名
                GetObjectRequest request       = new GetObjectRequest(null, null, localDir, localFileName);
                //设置下载请求预签名 URL
                request.RequestURLWithSign = requestSignURL;
                //设置进度回调
                request.SetCosProgressCallback(delegate(long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                GetObjectResult result = cosXml.GetObject(request);
                //请求成功
                Console.WriteLine(result.GetResultInfo());
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }

            //.cssg-snippet-body-end
        }
Example #2
0
        public void Download(string name)
        {
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct
                {
                    appid              = _cosSettings.AppId,                                // 腾讯云账号 APPID
                    region             = _cosSettings.Region,                               // 存储桶地域
                    bucket             = $"{_cosSettings.BucketName}-{_cosSettings.AppId}", // 存储桶
                    key                = name,                                              // 对象键
                    httpMethod         = "GET",                                             // HTTP 请求方法
                    isHttps            = true,                                              // 生成 HTTPS 请求 URL
                    signDurationSecond = 600,                                               // 请求签名时间为600s
                    headers            = null,                                              // 签名中需要校验的 header
                    queryParameters    = null                                               // 签名中需要校验的 URL 中请求参数
                };

                string requestSignUrl = _cosXml.GenerateSignURL(preSignatureStruct);

                //下载请求预签名 URL (使用永久密钥方式计算的签名 URL)
                //string localDir = System.IO.Path.GetTempPath();//本地文件夹
                //string localFileName = "my-local-temp-file"; //指定本地保存的文件名
                //GetObjectRequest request = new GetObjectRequest(null, null, localDir, localFileName);
                ////设置下载请求预签名 URL
                //request.RequestURLWithSign = requestSignURL;
                ////设置进度回调
                //request.SetCosProgressCallback(delegate (long completed, long total)
                //{
                //    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                //});
                ////执行请求
                //GetObjectResult result = cosXml.GetObject(request);
                ////请求成功
                //Console.WriteLine(result.GetResultInfo());
                Console.WriteLine(requestSignUrl);
            }
            catch (CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
        }
Example #3
0
        public void generateSignUrl()
        {
            QCloudServer       instance        = QCloudServer.Instance();
            string             key             = commonKey;
            PreSignatureStruct signatureStruct = new PreSignatureStruct();

            signatureStruct.bucket     = instance.bucketForObjectTest;
            signatureStruct.appid      = instance.appid;
            signatureStruct.region     = instance.region;
            signatureStruct.key        = key;
            signatureStruct.httpMethod = "GET";
            signatureStruct.headers    = new Dictionary <string, string>();
            string url = instance.cosXml.GenerateSignURL(signatureStruct);

            Console.WriteLine(url);
            Assert.NotNull(url);
        }
Example #4
0
        public Task <string> GetBlobUrl(string containerName, string blobName)
        {
            var preSignatureStruct = new PreSignatureStruct();

            preSignatureStruct.appid              = _tcConfig.AppId;               //腾讯云账号 APPID
            preSignatureStruct.region             = _tcConfig.Region;              //存储桶地域
            preSignatureStruct.bucket             = _tcConfig.BucketName;          //存储桶
            preSignatureStruct.key                = $"{containerName}/{blobName}"; //对象键
            preSignatureStruct.httpMethod         = "PUT";                         //HTTP 请求方法
            preSignatureStruct.isHttps            = true;                          //生成 HTTPS 请求 URL
            preSignatureStruct.signDurationSecond = 600;                           //请求签名时间为 600s
            preSignatureStruct.headers            = null;                          //签名中需要校验的 header
            preSignatureStruct.queryParameters    = null;                          //签名中需要校验的 URL 中请求参数

            var url = _cosXmlServer.GenerateSignURL(preSignatureStruct);

            return(Task.FromResult(url));
        }
Example #5
0
        /// <summary>
        ///     获取授权访问链接
        /// </summary>
        /// <param name="containerName">容器名称</param>
        /// <param name="blobName">文件名称</param>
        /// <param name="expiry">过期时间</param>
        /// <param name="isDownload">是否允许下载</param>
        /// <param name="fileName">文件名</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="access">访问限制</param>
        /// <returns></returns>
        public Task <string> GetBlobUrl(string containerName, string blobName, DateTime expiry, bool isDownload = false,
                                        string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var preSignatureStruct = new PreSignatureStruct();

            preSignatureStruct.appid              = _tcConfig.AppId;                            //腾讯云账号 APPID
            preSignatureStruct.region             = _tcConfig.Region;                           //存储桶地域
            preSignatureStruct.bucket             = _tcConfig.BucketName;                       //存储桶
            preSignatureStruct.key                = $"{containerName}/{blobName}";              //对象键
            preSignatureStruct.httpMethod         = "PUT";                                      //HTTP 请求方法
            preSignatureStruct.isHttps            = true;                                       //生成 HTTPS 请求 URL
            preSignatureStruct.signDurationSecond = (long)(expiry - DateTime.Now).TotalSeconds; //请求签名时间为 600s
            preSignatureStruct.headers            = null;                                       //签名中需要校验的 header
            preSignatureStruct.queryParameters    = null;                                       //签名中需要校验的 URL 中请求参数

            var url = _cosXmlServer.GenerateSignURL(preSignatureStruct);

            return(Task.FromResult(url));
        }
Example #6
0
        /// <summary>
        /// 请求腾讯云COS的API
        /// </summary>
        /// <param name="appid">腾讯云账号 APPID</param>
        /// <param name="region">存储桶地域</param>
        /// <param name="bucket">存储桶</param>
        /// <param name="key">对象键</param>
        /// <param name="param">额外参数</param>
        /// <returns>返回XML</returns>
        public static Stream TencentCOSGetHttpResponse(string appid, string region, string bucket, string key, string param = "")
        {
            if (!param.StartsWith("&"))
            {
                param = "&" + param;
            }

            PreSignatureStruct preSignatureStruct = new PreSignatureStruct();

            preSignatureStruct.appid              = appid;  //腾讯云账号 APPID
            preSignatureStruct.region             = region; //存储桶地域
            preSignatureStruct.bucket             = bucket; //存储桶
            preSignatureStruct.key                = key;    //对象键
            preSignatureStruct.httpMethod         = "GET";  //HTTP 请求方法
            preSignatureStruct.isHttps            = true;   //生成 HTTPS 请求 URL
            preSignatureStruct.signDurationSecond = 600;    //请求签名时间为 600s
            preSignatureStruct.headers            = null;   //签名中需要校验的 header
            preSignatureStruct.queryParameters    = null;   //签名中需要校验的 URL 中请求参数
            string requestSignURL = CosXml.GenerateSignURL(preSignatureStruct) + param;

            return(HttpHelper.GetHttpResponseStream(requestSignURL, out _));
        }
Example #7
0
        public string GenerateSignURL(PreSignatureStruct preSignatureStruct)
        {
            try
            {
                if (preSignatureStruct.httpMethod == null)
                {
                    throw new CosClientException((int)CosClientError.InvalidArgument, "httpMethod = null");
                }

                if (preSignatureStruct.key == null)
                {
                    throw new CosClientException((int)CosClientError.InvalidArgument, "key = null");
                }

                StringBuilder urlBuilder = new StringBuilder();

                if (preSignatureStruct.isHttps)
                {
                    urlBuilder.Append("https://");
                }
                else
                {
                    urlBuilder.Append("http://");
                }

                if (preSignatureStruct.host == null)
                {
                    StringBuilder host = new StringBuilder();

                    if (preSignatureStruct.bucket == null)
                    {
                        throw new CosClientException((int)CosClientError.InvalidArgument, "bucket = null");
                    }

                    if (preSignatureStruct.bucket.EndsWith("-" + preSignatureStruct.appid))
                    {
                        host.Append(preSignatureStruct.bucket);
                    }
                    else
                    {
                        host.Append(preSignatureStruct.bucket).Append("-")
                        .Append(preSignatureStruct.appid);
                    }

                    host.Append(".cos.")
                    .Append(preSignatureStruct.region)
                    .Append(".myqcloud.com");

                    urlBuilder.Append(host.ToString());

                    // host 入签
                    if (preSignatureStruct.signHost)
                    {
                        if (preSignatureStruct.headers == null)
                        {
                            preSignatureStruct.headers = new Dictionary <string, string>();
                        }
                        if (!preSignatureStruct.headers.ContainsKey("host"))
                        {
                            preSignatureStruct.headers.Add("host", host.ToString());
                        }
                    }
                }
                else
                {
                    urlBuilder.Append(preSignatureStruct.host);
                    // host 入签
                    if (preSignatureStruct.signHost)
                    {
                        if (preSignatureStruct.headers == null)
                        {
                            preSignatureStruct.headers = new Dictionary <string, string>();
                        }
                        preSignatureStruct.headers.Add("host", preSignatureStruct.host);
                    }
                }

                if (!preSignatureStruct.key.StartsWith("/"))
                {
                    preSignatureStruct.key = "/" + preSignatureStruct.key;
                }

                urlBuilder.Append(preSignatureStruct.key);

                string sign = GenerateSign(preSignatureStruct.httpMethod, preSignatureStruct.key,
                                           preSignatureStruct.queryParameters, preSignatureStruct.headers, preSignatureStruct.signDurationSecond);

                StringBuilder queryBuilder = new StringBuilder();

                if (preSignatureStruct.queryParameters != null && preSignatureStruct.queryParameters.Count > 0)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in preSignatureStruct.queryParameters)
                    {
                        if (keyValuePair.Key == null || keyValuePair.Key == "")
                        {
                            continue;
                        }
                        queryBuilder.Append(URLEncodeUtils.Encode(keyValuePair.Key)).Append('=').Append(URLEncodeUtils.Encode(keyValuePair.Value));
                        queryBuilder.Append('&');
                    }
                }

                // 针对需要二次 Encode 的 request Param 特殊处理
                Regex  rgx       = new Regex("q-url-param-list=.*&q-signature");
                string paramlist = rgx.Match(sign).ToString().Split('=')[1].ToString().Split('&')[0].ToString();
                paramlist = paramlist.Trim('&');
                paramlist = URLEncodeUtils.Encode(paramlist).ToLower();
                string encodedStr = "q-url-param-list=" + paramlist + "&q-signature";
                sign = rgx.Replace(sign, encodedStr);

                queryBuilder.Append(sign);
                urlBuilder.Append("?").Append(queryBuilder.ToString());

                return(urlBuilder.ToString());
            }
            catch (CosClientException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CosClientException((int)CosClientError.InvalidArgument, ex.Message, ex);
            }
        }
Example #8
0
        public string GenerateSignURL(PreSignatureStruct preSignatureStruct)
        {
            try
            {
                if (preSignatureStruct.httpMethod == null)
                {
                    throw new CosClientException((int)CosClientError.InvalidArgument, "httpMethod = null");
                }

                if (preSignatureStruct.key == null)
                {
                    throw new CosClientException((int)CosClientError.InvalidArgument, "key = null");
                }

                StringBuilder urlBuilder = new StringBuilder();

                if (preSignatureStruct.isHttps)
                {
                    urlBuilder.Append("https://");
                }
                else
                {
                    urlBuilder.Append("http://");
                }

                if (preSignatureStruct.host == null)
                {
                    if (preSignatureStruct.bucket == null)
                    {
                        throw new CosClientException((int)CosClientError.InvalidArgument, "bucket = null");
                    }

                    if (preSignatureStruct.bucket.EndsWith("-" + preSignatureStruct.appid))
                    {
                        urlBuilder.Append(preSignatureStruct.bucket);
                    }
                    else
                    {
                        urlBuilder.Append(preSignatureStruct.bucket).Append("-")
                        .Append(preSignatureStruct.appid);
                    }

                    urlBuilder.Append(".cos.")
                    .Append(preSignatureStruct.region)
                    .Append(".myqcloud.com");
                }
                else
                {
                    urlBuilder.Append(preSignatureStruct.host);
                }

                if (!preSignatureStruct.key.StartsWith("/"))
                {
                    preSignatureStruct.key = "/" + preSignatureStruct.key;
                }

                urlBuilder.Append(preSignatureStruct.key);

                string sign = GenerateSign(preSignatureStruct.httpMethod, preSignatureStruct.key,
                                           preSignatureStruct.queryParameters, preSignatureStruct.headers, preSignatureStruct.signDurationSecond);

                StringBuilder queryBuilder = new StringBuilder();

                if (preSignatureStruct.queryParameters != null && preSignatureStruct.queryParameters.Count > 0)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in preSignatureStruct.queryParameters)
                    {
                        queryBuilder.Append(keyValuePair.Key).Append('=').Append(URLEncodeUtils.Encode(keyValuePair.Value));
                        queryBuilder.Append('&');
                    }
                }

                queryBuilder.Append(sign);
                urlBuilder.Append("?").Append(queryBuilder.ToString());

                return(urlBuilder.ToString());
            }
            catch (CosClientException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CosClientException((int)CosClientError.InvalidArgument, ex.Message, ex);
            }
        }
Example #9
0
        //临时密钥预签名请求示例-下载
        public string DownGetUrl()
        {
            try
            {
                CosXmlConfig config = new CosXmlConfig.Builder()
                                      .SetConnectionTimeoutMs(60000) //设置连接超时时间,单位 毫秒 ,默认 45000ms
                                      .SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位 毫秒 ,默认 45000ms
                                      .IsHttps(true)                 //设置默认 https 请求
                                      .SetAppid(AppID)               //设置腾讯云账户的账户标识 APPID
                                      .SetRegion(AppTong)            //设置一个默认的存储桶地域
                                      .SetDebugLog(true)             //显示日志
                                      .Build();                      //创建 CosXmlConfig 对象
                string secretId       = SecretId;                    //"云 API 密钥 SecretId";
                string secretKey      = SecretKey;                   //"云 API 密钥 SecretKey";
                long   durationSecond = 600;                         //secretKey 有效时长,单位为 秒
                QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);
                CosXmlServer             cosXml = new CosXmlServer(config, cosCredentialProvider);

                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid              = AppID;      //腾讯云账号 appid
                preSignatureStruct.region             = AppTong;    //存储桶地域
                preSignatureStruct.bucket             = Cct;        //存储桶
                preSignatureStruct.key                = Dxj;        //对象键
                preSignatureStruct.httpMethod         = "GET";      //http 请求方法
                preSignatureStruct.isHttps            = true;       //生成 https 请求URL
                preSignatureStruct.signDurationSecond = 600;        //请求签名时间为 600s
                preSignatureStruct.headers            = null;       //签名中需要校验的header
                preSignatureStruct.queryParameters    = null;       //签名中需要校验的URL中请求参数

                return(cosXml.GenerateSignURL(preSignatureStruct)); //载请求预签名 URL (使用永久密钥方式计算的签名 URL )

                #region 临时密钥下载

                ////使用临时密钥初始化 CosXml
                //CosXmlConfig config = new CosXmlConfig.Builder()
                //.SetConnectionTimeoutMs(60000)  //设置连接超时时间,单位 毫秒 ,默认 45000ms
                //.SetReadWriteTimeoutMs(40000)  //设置读写超时时间,单位 毫秒 ,默认 45000ms
                //.IsHttps(true)  //设置默认 https 请求
                //.SetAppid(AppID)  //设置腾讯云账户的账户标识 APPID
                //.SetRegion(AppTong)  //设置一个默认的存储桶地域
                //.SetDebugLog(true)  //显示日志
                //.Build();  //创建 CosXmlConfig 对象
                //string tmpSecretId = SecretId; //"临时密钥 SecretId";
                //string tmpSecretKey = SecretKey; //"临时密钥 SecretKey";
                //string tmpToken = Token; //"临时密钥 token";
                //long tmpExpireTime = ConvertDateTimeInt(DateTime.Now);//临时密钥有效截止时间
                //QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(tmpSecretId, tmpSecretKey, tmpExpireTime, tmpToken);
                //CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider);

                //PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                //preSignatureStruct.appid = AppID;//腾讯云账号 appid
                //preSignatureStruct.region = AppTong; //存储桶地域
                //preSignatureStruct.bucket = Cct; //存储桶
                //preSignatureStruct.key = Dxj; //对象键
                //preSignatureStruct.httpMethod = "GET"; //http 请求方法
                //preSignatureStruct.isHttps = true; //生成 https 请求URL
                //preSignatureStruct.signDurationSecond = 600; //请求签名时间为 600s
                //preSignatureStruct.headers = null;//签名中需要校验的header
                //preSignatureStruct.queryParameters = null; //签名中需要校验的URL中请求参数
                //return cosXml.GenerateSignURL(preSignatureStruct); //载请求预签名 URL (使用临时密钥方式计算的签名 URL )

                #endregion 临时密钥下载
            }
            catch (Exception)
            {
                return("");
            }
        }
        private async Task <string> PresignedObjectAsync(string bucketName, string objectName, int expiresInt, PresignedObjectType type)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException(nameof(bucketName));
            }
            if (string.IsNullOrEmpty(objectName))
            {
                throw new ArgumentNullException(nameof(objectName));
            }
            if (expiresInt <= 0)
            {
                throw new Exception("ExpiresIn time can not less than 0.");
            }
            if (expiresInt > 7 * 24 * 3600)
            {
                throw new Exception("ExpiresIn time no more than 7 days.");
            }
            long               nowTime            = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            const int          minExpiresInt      = 600;
            string             key                = Encrypt.MD5($"{bucketName}_{objectName}_{type.ToString().ToUpper()}");
            string             objectUrl          = null;
            string             newBucketName      = ConvertBucketName(bucketName);
            PreSignatureStruct preSignatureStruct = new PreSignatureStruct()
            {
                appid              = Options.Endpoint,
                region             = Options.Region,
                bucket             = newBucketName,
                key                = objectName,
                httpMethod         = type.ToString().ToUpper(),
                isHttps            = Options.IsEnableHttps,
                signDurationSecond = expiresInt,
                headers            = null,
                queryParameters    = null,
            };

            //查找缓存
            if (Options.IsEnableCache && (expiresInt > minExpiresInt))
            {
                var cacheResult = await _cache.GetAsync <PresignedUrlCache>(key);

                PresignedUrlCache cache = cacheResult.HasValue ? cacheResult.Value : null;
                //缓存中存在,且有效时间不低于10分钟
                if (cache != null &&
                    cache.Type == type &&
                    cache.CreateTime > 0 &&
                    (cache.CreateTime + expiresInt - nowTime) > minExpiresInt &&
                    cache.Name == objectName &&
                    cache.BucketName == bucketName)
                {
                    return(cache.Url);
                }
            }
            if (type == PresignedObjectType.Get)
            {
                //生成URL
                AccessMode accessMode = await this.GetObjectAclAsync(bucketName, objectName);

                if (accessMode == AccessMode.PublicRead || accessMode == AccessMode.PublicReadWrite)
                {
                    objectUrl = $"{(Options.IsEnableHttps ? "https" : "http")}://{newBucketName}.cos.{Options.Region}.myqcloud.com{(objectName.StartsWith("/") ? "" : "/")}{objectName}";
                }
                else
                {
                    string uri = _client.GenerateSignURL(preSignatureStruct);
                    if (uri != null)
                    {
                        objectUrl = uri.ToString();
                    }
                }
            }
            else
            {
                string uri = _client.GenerateSignURL(preSignatureStruct);
                if (uri != null)
                {
                    objectUrl = uri.ToString();
                }
            }
            if (string.IsNullOrEmpty(objectUrl))
            {
                throw new Exception("Presigned get object url failed.");
            }
            //save cache
            if (Options.IsEnableCache && expiresInt > minExpiresInt)
            {
                PresignedUrlCache urlCache = new PresignedUrlCache()
                {
                    Url        = objectUrl,
                    CreateTime = nowTime,
                    Name       = objectName,
                    BucketName = bucketName,
                    Type       = type
                };
                int randomSec = new Random().Next(5, 30);
                await _cache.SetAsync(key, urlCache, TimeSpan.FromSeconds(expiresInt + randomSec));
            }
            return(objectUrl);
        }