在介绍Blob容器的访问权限与策略设置之前,我们先来明确一下两个概念。
第一,对容器的访问,指的是什么?简单来说,就是对容器的增删改查操作。其中增是指往容器里面写入数据,删是删除容器里头Blob文件,改与增类似,而查是指列出容器下所有的Blob文件。
第二,两个角色:
- 所有者(Owner of storage account)
- 匿名用户
所有者,即是通过账户名称与密钥来访问storage的人。
匿名用户,即是通过类似http://yourdomain.blob.core.windows.net/这样的Endpoint来访问storage的人。
(其中,账户名称、访问密钥、Endpoint地址都可以从Azure Management Portal中获取。)
Blob容器的权限设置,都是针对匿名用户来说的,所有者不存在权限问题,不管怎么设置,所有者都能够访问所有内容,做所有操作。
设置Blob容器的访问权限,包含两种方式,一种是通过设置Public Access,另外一种是比较细粒度的SharedAccessPolicies。
对于Public Access设置,比较简单,如下代码所示:
blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
BlobContainerPublicAccessType枚举包含三项:
public enum BlobContainerPublicAccessType
{
Off,
Container,
Blob
}
Off:不允许匿名用户读取该容器中的Blob;
Container:匿名用户可以读取该容器的Blob;
Blob:匿名用户只能读取Blob,即只能根据Blob的URL来读取Blob,无法列出容器下所有的Blob。
我们发现,使用Public Access只能配置匿名用户的读取权限,如果希望匿名用户同样有增删的权限怎么办呢?
这个时候就需要用到SharedAccessPolicies。接下来重点介绍一下SharedAccessPolicies的使用。
在这个例子中,我将使用一个普通的Web应用程序,来访问位于云端的Blob Storage。我们先来看一下页面结构:
页面非常简单,红框内模拟的是所有者给容器设置访问策略。填写设置信息后,点击Set Permission后,进行策略设置,并生成签名。
其中包含四个访问权限,Read表示是否能读取Blob,Write表示是否能往容器里面写入Blob,Delete表示能否删除Blob文件,List表示能否列出容器里的所有Blob文件。
Start Time表示多长时间以后设置的策略生效,Expiry Time表示策略多长时间以后失效,单位均是秒。
篮框内模拟匿名用户使用签名来访问容器。List Blob列出容器下所有Blob,Upload往容器里添加Blob,点击链接下载Blob,点击Delete删除Blob。
所有者设置访问策略代码如下:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference("mycontainer");
blobContainer.CreateIfNotExists();
BlobContainerPermissions blobPermissions = new BlobContainerPermissions();
blobPermissions.PublicAccess = BlobContainerPublicAccessType.Off;
SharedAccessBlobPolicy myPolicy = new SharedAccessBlobPolicy();
//Create permissions according to what you selected
SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.None;
if (CanRead.Checked)
{
permissions = SharedAccessBlobPermissions.Read;
}
if (CanWrite.Checked)
{
if (permissions == SharedAccessBlobPermissions.None)
{
permissions = SharedAccessBlobPermissions.Write;
}
else
{
permissions = permissions | SharedAccessBlobPermissions.Write;
}
}
if (CanDelete.Checked)
{
if (permissions == SharedAccessBlobPermissions.None)
{
permissions = SharedAccessBlobPermissions.Delete;
}
else
{
permissions = permissions | SharedAccessBlobPermissions.Delete;
}
}
if (CanList.Checked)
{
if (permissions == SharedAccessBlobPermissions.None)
{
permissions = SharedAccessBlobPermissions.List;
}
else
{
permissions = permissions | SharedAccessBlobPermissions.List;
}
}
myPolicy.Permissions = permissions;
int accessStartSeconds = 0;
if (int.TryParse(AccessStartTime.Text, out accessStartSeconds))
{
myPolicy.SharedAccessStartTime = DateTimeOffset.UtcNow.AddSeconds(accessStartSeconds);
}
int accessExpirySeconds = 0;
if (int.TryParse(AccessExpiryTime.Text, out accessExpirySeconds))
{
myPolicy.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddSeconds(accessExpirySeconds);
}
//Add the policy to Blob permissions' SharedAccessPolicies
//You can add more than one policy
blobPermissions.SharedAccessPolicies.Add("mypolicy", myPolicy);
//Set the container's permissions
blobContainer.SetPermissions(blobPermissions);
//Get the Signature of "mypolicy"
string sasToken = blobContainer.GetSharedAccessSignature(myPolicy);
Signature.Text = sasToken;
List Blob代码如下:
(注意到在创建CloudBlobClient时没有用到Storage账户名称与密钥,而是通过终结点与策略签名来创建,表明这是匿名用户访问。)
try
{
CloudStorageAccount storageAccount =
CloudStorageAccount.Parse(StorageConnectionString);
StorageCredentials credentials = new StorageCredentials(Signature.Text);
CloudBlobClient blobClient = new CloudBlobClient(storageAccount.BlobEndpoint, credentials);
CloudBlobContainer blobContainer = blobClient.GetContainerReference("mycontainer");
//blobContainer.CreateIfNotExists();
IEnumerable<IListBlobItem> blobItems = blobContainer.ListBlobs(null, true, BlobListingDetails.None, null, null);
List<CloudBlockBlob> blockBlobs = new List<CloudBlockBlob>();
foreach (IListBlobItem item in blobItems)
{
if (item.GetType() == typeof(CloudBlockBlob))
{
blockBlobs.Add((CloudBlockBlob)item);
}
}
BlobItemGridView.DataSource = blockBlobs;
BlobItemGridView.DataBind();
ErrorMsg.Text = "";
}
catch (Exception ex)
{
ErrorMsg.Text = ex.Message;
}
Upload文件至容器:
try
{
if (FileUpload1.HasFile)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageConnectionString);
StorageCredentials credentials = new StorageCredentials(Signature.Text);
CloudBlobClient blobClient = new CloudBlobClient(storageAccount.BlobEndpoint, credentials);
CloudBlobContainer blobContainer = blobClient.GetContainerReference("mycontainer");
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(FileUpload1.FileName);
blockBlob.UploadFromStream(FileUpload1.FileContent);
ErrorMsg.Text = "";
}
}
catch (Exception ex)
{
ErrorMsg.Text = ex.Message;
}
删除Blob文件:
try
{
Uri uri = e.Keys[0] as Uri;
StorageCredentials credentials = new StorageCredentials(Signature.Text);
CloudBlockBlob blob = new CloudBlockBlob(uri, credentials);
blob.DeleteIfExists(DeleteSnapshotsOption.None);
List_Click(null, null);
ErrorMsg.Text = "";
}
catch (Exception ex)
{
ErrorMsg.Text = ex.Message;
}
下载Blob文件:
try
{
string uri = e.CommandArgument.ToString();
StorageCredentials credentials = new StorageCredentials(Signature.Text);
CloudBlockBlob blockBlob = new CloudBlockBlob(new Uri(uri), credentials);
var memoryStream = new MemoryStream();
if (blockBlob.Exists())
{
blockBlob.DownloadToStream(memoryStream);
HttpUtils.WriteFileToResponse(this, memoryStream, Path.GetFileName(uri), true, Path.GetExtension(uri));
ErrorMsg.Text = "";
}
else
{
ErrorMsg.Text = "The Blob doesn't exist";
}
}
catch (Exception ex)
{
ErrorMsg.Text = ex.Message;
}
我们只给Read与List的权限,然后尝试删除或者上传Blob文件,将会产生一个异常:
同理,我们可以自己来做其他策略组合的测试。
在整个Windows Azure Storage中,包含了Queue, Table和Blob,这里只是以Blob做例子演示了访问权限和策略的配置,其实对于另外两个存储也类似。有兴趣的朋友可以自己尝试一下。
点击 这里 下载源码。