public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false, 
            string filename = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var blob = _blobClient.GetContainerReference(containerName)
                .GetBlockBlobReference(blobName);

            var builder = new UriBuilder(blob.Uri);
            var headers = new SharedAccessBlobHeaders();
            var hasFilename = !string.IsNullOrEmpty(filename);

            if (hasFilename || isDownload)
            {
                headers.ContentDisposition = "attachment" + (hasFilename ? "; filename=\"" + filename + "\"" : string.Empty);
            }

            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }

            builder.Query = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions = access.ToPermissions(),
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = expiry,
            }, headers).TrimStart('?');

            return builder.Uri.ToString();
        }
Esempio n. 2
0
        public static SharedAccessBlobPermissions ToPermissions(this BlobUrlAccess security)
        {
            switch (security)
            {
            case BlobUrlAccess.Read:
                return(SharedAccessBlobPermissions.Read);

            case BlobUrlAccess.Write:
                return(SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Write);

            case BlobUrlAccess.Delete:
                return(SharedAccessBlobPermissions.Delete);

            case BlobUrlAccess.All:
                return(SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Delete | SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write);

            default:
                return(SharedAccessBlobPermissions.None);
            }
        }
Esempio n. 3
0
        public override async Task <string> GetTemporaryFileUrl(Uri baseUri, StoredFile storedFile,
                                                                StorageSettings configuration, DateTimeOffset expiry, bool isDownload,
                                                                BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var localFileDescriptor = new TemporaryLocalFileDescriptor()
            {
                Expiry     = expiry,
                FileId     = storedFile.Id,
                IsDownload = isDownload
            };
            var name     = Guid.NewGuid().ToString();
            var fullPath = Path.Combine(_datadirs.Value.TempStorageDir, name);

            if (!File.Exists(fullPath))
            {
                File.Create(fullPath).Dispose();
            }

            await File.WriteAllTextAsync(Path.Combine(_datadirs.Value.TempStorageDir, name), JsonConvert.SerializeObject(localFileDescriptor));

            return(new Uri(baseUri, $"{LocalStorageDirectoryName}tmp/{name}{(isDownload ? "?download" : string.Empty)}").AbsoluteUri);
        }
Esempio n. 4
0
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry,
                                    bool isDownload      = false, string fileName = null, string contentType = null,
                                    BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var headers = new ResponseHeaderOverrides();

            if (isDownload)
            {
                headers.ContentDisposition = "attachment;";
            }
            if (!string.IsNullOrEmpty(fileName))
            {
                headers.ContentDisposition += "filename=\"" + fileName + "\"";
            }
            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }
            var urlRequest = new GetPreSignedUrlRequest()
            {
                BucketName = _bucket,
                Key        = GenerateKeyName(containerName, blobName),
                Expires    = expiry.UtcDateTime,
                ResponseHeaderOverrides = headers,
                Verb = access == BlobUrlAccess.Read ? HttpVerb.GET : HttpVerb.PUT
            };

            try
            {
                return(_s3Client.GetPreSignedURL(urlRequest));
            }
            catch (AmazonS3Exception asex)
            {
                throw asex.ToStorageException();
            }
        }
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
                                    string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var headers = new ResponseHeaderOverrides();

            ContentDispositionHeaderValue cdHeader;

            if (isDownload)
            {
                cdHeader = new ContentDispositionHeaderValue("attachment");
            }
            else
            {
                cdHeader = new ContentDispositionHeaderValue("inline");
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                cdHeader.FileNameStar = fileName;
            }

            headers.ContentDisposition = cdHeader.ToString();

            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }

            var urlRequest = new GetPreSignedUrlRequest
            {
                BucketName = _bucket,
                Key        = GenerateKeyName(containerName, blobName),
                Expires    = expiry.UtcDateTime,
                ResponseHeaderOverrides = headers,
                Verb = access == BlobUrlAccess.Read ? HttpVerb.GET : HttpVerb.PUT
            };

            if (!string.IsNullOrEmpty(_serverSideEncryptionMethod))
            {
                urlRequest.ServerSideEncryptionMethod = _serverSideEncryptionMethod;
            }

            try
            {
                return(_s3Client.GetPreSignedURL(urlRequest));
            }
            catch (AmazonS3Exception asex)
            {
                throw asex.ToStorageException();
            }
        }
 public override Task <string> GetTemporaryFileUrl(StoredFile storedFile, StorageSettings configuration, DateTimeOffset expiry, bool isDownload,
                                                   BlobUrlAccess access = BlobUrlAccess.Read)
 {
     return(GetFileUrl(storedFile, configuration));
 }
 /// <inheritdoc/>
 public Task <string> GetBlobUrl(string containerName, string blobName, DateTime expiry, bool isDownload = false, string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
 {
     throw new NotImplementedException();
 }
Esempio n. 8
0
 public override async Task <string> GetTemporaryFileUrl(StoredFile storedFile, StorageSettings configuration, DateTimeOffset expiry, bool isDownload,
                                                         BlobUrlAccess access = BlobUrlAccess.Read)
 {
     return($"{(await GetFileUrl(storedFile, configuration))}{(isDownload ? "?download" : string.Empty)}");
 }
        /// <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 request = new GetPreSignedUrlRequest
            {
                BucketName  = _tcConfig.BucketName,
                Key         = $"{containerName}/{blobName}",
                Expires     = expiry,
                ContentType = contentType
            };

            var url = _amazonS3Client.GetPreSignedURL(request);

            return(Task.FromResult(url));
        }
Esempio n. 10
0
 public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry,
                             bool isDownload = false, string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
 {
     return(Path.Combine(_basePath, containerName, blobName));
 }
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false, 
            string filename = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var blob = _blobClient.GetContainerReference(containerName)
                .GetBlockBlobReference(blobName);

            var builder = new UriBuilder(blob.Uri);
            var headers = new SharedAccessBlobHeaders();
            var hasFilename = !string.IsNullOrEmpty(filename);

            if (hasFilename || isDownload)
            {
                headers.ContentDisposition = "attachment" + (hasFilename ? "; filename=\"" + filename + "\"" : string.Empty);
            }

            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }

            builder.Query = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions = access.ToPermissions(),
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = expiry,
            }, headers).TrimStart('?');

            return builder.Uri.ToString();
        }
Esempio n. 12
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));
        }
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
            string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var headers = new ResponseHeaderOverrides();

            if (isDownload)
            {
                headers.ContentDisposition = "attachment;";
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                headers.ContentDisposition += "filename=\"" + fileName + "\"";
            }

            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }

            var urlRequest = new GetPreSignedUrlRequest()
            {
                BucketName = _bucket,
                Key = GenerateKeyName(containerName, blobName),
                Expires = expiry.UtcDateTime,
                ResponseHeaderOverrides = headers,
                Verb = access == BlobUrlAccess.Read ? HttpVerb.GET : HttpVerb.PUT
            };

            try
            {
                return _s3Client.GetPreSignedURL(urlRequest);
            }
            catch (AmazonS3Exception asex)
            {
                throw asex.ToStorageException();
            }
        }
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
                                    string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var blob = _blobClient.GetContainerReference(containerName)
                       .GetBlockBlobReference(blobName);

            var builder = new UriBuilder(blob.Uri);
            var headers = new SharedAccessBlobHeaders();

            ContentDispositionHeaderValue cdHeader;

            if (isDownload)
            {
                cdHeader = new ContentDispositionHeaderValue("attachment");
            }
            else
            {
                cdHeader = new ContentDispositionHeaderValue("inline");
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                cdHeader.FileNameStar = fileName;
            }

            headers.ContentDisposition = cdHeader.ToString();

            if (!string.IsNullOrEmpty(contentType))
            {
                headers.ContentType = contentType;
            }

            builder.Query = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions            = access.ToPermissions(),
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = expiry,
            }, headers).TrimStart('?');

            return(builder.Uri.ToString());
        }
        // TODO: Currently google only support adding a content disposition when uploading
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
                                    string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var expiration = expiry.ToUnixTimeSeconds();
            //var disp = fileName != null ? "content-disposition:attachment;filename=\"" + fileName +"\"" : string.Empty;
            var verb         = access == BlobUrlAccess.Read ? "GET" : "PUT";
            var urlSignature = SignString($"{verb}\n\n{contentType}\n{expiration}\n/{_bucket}/{containerName}/{blobName}");

            return($"https://storage.googleapis.com/{_bucket}/{containerName}/{blobName}?GoogleAccessId={_serviceEmail}&Expires={expiration}&Signature={WebUtility.UrlEncode(urlSignature)}");
        }
        /// <inheritdoc/>
        public async Task <string> GetBlobUrl(string containerName, string blobName, DateTime expiry,
                                              bool isDownload = false,
                                              string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            try
            {
                var httpMethod = SignHttpMethod.Get;
                return(await Task.Run(() =>
                {
                    switch (access)
                    {
                    case BlobUrlAccess.Read:
                        httpMethod = SignHttpMethod.Get;
                        break;

                    case BlobUrlAccess.All:
                    case BlobUrlAccess.Write:
                        httpMethod = SignHttpMethod.Put;
                        break;

                    case BlobUrlAccess.Delete:
                        httpMethod = SignHttpMethod.Delete;
                        break;

                    default:
                        throw new StorageException(StorageErrorCode.InvalidAccess.ToStorageError(),
                                                   new Exception("无效的访问凭据"));
                    }

                    var req = new GeneratePresignedUriRequest(containerName, blobName, httpMethod)
                    {
                        Expiration = expiry
                    };
                    var url = _ossClient.GeneratePresignedUri(req);
                    return url.AbsoluteUri;
                }));
            }
            catch (Exception ex)
            {
                throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
                                           new Exception(ex.ToString()));
            }
        }
Esempio n. 17
0
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
                                    string fileName = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            if (_urlSigner == null)
            {
                throw new StorageException(StorageErrorCode.InvalidCredentials, "URL Signer requires ServiceAccountCredentials");
            }

            var headers = new Dictionary <string, IEnumerable <string> >();

            if (!string.IsNullOrEmpty(fileName))
            {
                var header = $"filename=\"{fileName}\"";

                headers["Content-Disposition"] = new[] { isDownload ? "attachment; " + header : header };
            }
            else if (isDownload)
            {
                headers["Content-Disposition"] = new[] { "attachment;" };
            }

            if (!string.IsNullOrEmpty(contentType))
            {
                headers["Content-Type"] = new[] { contentType };
            }

            return(_urlSigner.Sign(
                       _bucket,
                       ObjectName(containerName, blobName),
                       expiry,
                       access == BlobUrlAccess.Read ? HttpMethod.Get : HttpMethod.Put,
                       headers));
        }
        public virtual async Task <string> GetTemporaryFileUrl(StoredFile storedFile, StorageSettings configuration,
                                                               DateTimeOffset expiry, bool isDownload, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var providerConfiguration = GetProviderConfiguration(configuration);
            var provider = await GetStorageProvider(providerConfiguration);

            if (isDownload)
            {
                var descriptor =
                    await provider.GetBlobDescriptorAsync(providerConfiguration.ContainerName,
                                                          storedFile.StorageFileName);

                return(provider.GetBlobSasUrl(providerConfiguration.ContainerName, storedFile.StorageFileName, expiry,
                                              true, storedFile.FileName, descriptor.ContentType, access));
            }

            return(provider.GetBlobSasUrl(providerConfiguration.ContainerName, storedFile.StorageFileName, expiry,
                                          false, null, null, access));
        }
Esempio n. 19
0
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false,
                                    string filename = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var req = new GeneratePresignedUriRequest(containerName, blobName)
            {
                Expiration = expiry.DateTime
            };

            switch (access)
            {
            case BlobUrlAccess.None:
            case BlobUrlAccess.Read:
                req.Method = SignHttpMethod.Get;
                break;

            case BlobUrlAccess.Write:
                req.Method = SignHttpMethod.Put;
                break;

            case BlobUrlAccess.Delete:
                throw new NotSupportedException("BlobUrlAccess.Delete");

            case BlobUrlAccess.All:
                throw new NotSupportedException("BlobUrlAccess.All");
            }
            if (!string.IsNullOrWhiteSpace(contentType))
            {
                req.ContentType = contentType;
            }

            if (!string.IsNullOrWhiteSpace(filename))
            {
                req.ResponseHeaders.ContentDisposition = "inline;filename=" + filename;
            }

            var uri = _ossClient.GeneratePresignedUri(req);

            return(uri.ToString());
        }