Azure Lei Zhang的博客

weibo: LeiZhang的微博/QQ: 185165016/QQ群:319036205/邮箱:leizhang1984@outlook.com/TeL:139-161-22926

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  《Windows Azure Platform 系列文章目录

 

  我们知道,Azure Blob Storage的安全性,是通过SAS来实现的。

  

 

  我们在使用Azure Storage SAS Token的时候,有两种设计模式:

  第一种:客户端上传至服务器端,服务器将文件上传至Azure Storage

  (1)客户端到服务器端,有单独的验证方式。比如AD验证,或者MySQL验证

  (2)验证通过后,客户端把数据保存到服务器端

  (3)服务器端保存Azure Storage Account Name和Account key。服务器端收到数据后,通过SAS Token上传到Azure Storage

  在这种场景中,客户端把数据保存到服务器端,然后服务器端把数据保存到Azure Storage

 

  第二种:客户端向服务器端申请SAS Token,从客户端通过SAS上传至Azure Storage

  (1))客户端到服务器端,有单独的验证方式。比如AD验证,或者MySQL验证

  (2)服务器端保存Azure Storage Account Name和Account key

  (3)验证通过后,服务器端向Azure Storage申请SAS Token。并将SAS Token返回给客户端

  (4)客户端获得SAS Token后,向Azure Storage上传数据

  在这种场景中,数据不会从客户端上传到服务器端

 

  具体设计如下图:

  

 

  具体的sample code如下:

  1.首先,获得一个blobclient

var connectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
    storageAccountName, // your storage account name
    accessKey); // your storage account access key
var storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("my-container");

  

  2.设置权限,申请SAS Token

SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30);
sasConstraints.Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create;

var blob = container.GetBlockBlobReference("outputfile.txt");
Console.WriteLine("{0}{1}",
    blob.Uri, blob.GetSharedAccessSignature(sasConstraints));

 

  SAS Token URL类似如下信息:

   https://mystoraget.blob.core.windows.net/my-container/myfile.txt?sv=2015-12-11&sr=b&sig=9UZXdW5eqoN7aiKqvnUo60gBAr1Y2feVNnIn2Hh2iU4%3D&se=2017-02-05T12%3A52%3A34Z&sp=cw

  

  3.通过SAS Token,将本地文件进行上传

var sas = "https://mystorageacct.blob.core.windows.net/..."; 
var cloudBlockBlob = new CloudBlockBlob(new Uri(sas));
await cloudBlockBlob.UploadFromFileAsync(@"c:\myfile.txt");

 

   4.我们也可以通过REST API进行上传

var client = new HttpClient();
var content = new StringContent("Some content");
content.Headers.Add("x-ms-blob-type", "BlockBlob");
var response = await client.PutAsync(sas, content);
response.EnsureSuccessStatusCode();

 

posted on 2019-12-14 19:57  Lei Zhang的博客  阅读(490)  评论(0编辑  收藏  举报