英文:
Combining two functions to generate token and read blob file content
问题
[FunctionName("SasTokenFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("formsample");
SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
};
string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";
// Get the SAS Token with content and return it to the client app
string sasTokenWithContent = GetUserDelegationSasBlobwithcontent();
return (ActionResult)new OkObjectResult(sasUriToken + sasTokenWithContent);
}
public static string GetUserDelegationSasBlobwithcontent()
{
string storageAccountUriString = "https://formsample5.blob.core.windows.net";
var credential = new DefaultAzureCredential();
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample"); //container name
BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");
// Get a user delegation key
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = blobClient.BlobContainerName,
BlobName = blobClient.Name,
Resource = "b", // b for blob, c for container
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
};
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); // read permissions
string sasToken = sasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName).ToString();
Console.WriteLine("SAS-Token {0}", sasToken);
Uri blobUri = new Uri(blobClient.Uri + "?" + sasToken);
BlobClient sasBlobClient = new BlobClient(blobUri);
BlobDownloadInfo download = sasBlobClient.Download();
var content = download.Content;
string contentString = string.Empty;
using (var streamReader = new StreamReader(content))
{
while (!streamReader.EndOfStream)
{
string line = streamReader.ReadLineAsync().Result;
contentString += $"\nBlob-contents:{line}";
}
}
return contentString;
}
英文:
I'm new to c#, as I'm working on developing Azure function to generate SAS token, and reading and modifying .docx blob file.
I have these two functions below to do the 2 tasks. However, I want to integrate them into one function. I've tried to do so, but there's something missing I couldn't understand.
[FunctionName("SasTokenFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("formsample");
SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
};
string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";
// return the SAS Token to the client app
GetUserDelegationSasBlobwithcontent();
return (ActionResult)new OkObjectResult(sasUriToken);
}
public static async void GetUserDelegationSasBlobwithcontent()
{
string storageAccountUriString = $"https://formsample5.blob.core.windows.net";
var credential = new DefaultAzureCredential();
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample"); //container name
BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");
// Get a user delegation key
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = blobClient.BlobContainerName,
BlobName = blobClient.Name,
Resource = "b", // b for blob, c for container
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
};
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); // read permissions
string sasToken = sasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName).ToString();
Console.WriteLine("SAS-Token {0}", sasToken);
Uri blobUri = new Uri(blobClient.Uri + "?" + sasToken);
BlobClient sasBlobClient = new BlobClient(blobUri);
BlobDownloadInfo download = sasBlobClient.Download();
var content = download.Content;
using (var streamReader = new StreamReader(content))
{
while (!streamReader.EndOfStream)
{
string line = await streamReader.ReadLineAsync();
Console.WriteLine("\nBlob-contents:{0}", line);
}
}
}
答案1
得分: 1
感谢Peter Csala
的评论。
要将这两个功能结合在一起,您需要修改
GetUserDelegationSasBlobwithcontent()
函数的返回类型,使其返回blob文件的内容作为字符串或字节数组。然后,您可以在Run()
函数内调用此函数,并将SAS令牌作为参数传递给GetUserDelegationSasBlobwithcontent()
函数。
要将这两个功能整合在一起,您可以修改GetUserDelegationSasBlobwithcontent
函数以返回blob文件的内容。然后,您可以在SasTokenFunction
中调用此函数,并将结果返回给客户端应用程序。
以下是需要在代码中使用的命名空间:
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Azure.Storage.Blobs;
using Azure.Identity;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
我使用了这段代码,并成功获取了令牌。
public static class Function1
{
[FunctionName("SasTokenFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("samplecontainer");
SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
};
string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";
string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);
return (ActionResult)new OkObjectResult(sasUriToken);
}
public static async Task<string> GetUserDelegationSasBlobwithcontent(string sasToken)
{
string storageAccountUriString = "https://formsample5.blob.core.windows.net";
var credential = new DefaultAzureCredential();
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample"); //container name
BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");
Uri blobUri = new Uri(blobClient.Uri + "?" + sasToken);
BlobClient sasBlobClient = new BlobClient(blobUri);
BlobDownloadInfo download = sasBlobClient.Download();
var content = download.Content;
using (var streamReader = new StreamReader(content))
{
string blobContent = await streamReader.ReadToEndAsync();
return blobContent;
}
}
}
令牌生成
获取SAS令牌的示例代码:
const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=<storage-account>;AccountKey=<account-key>";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
Permissions = SharedAccessAccountPermissions.Read |
SharedAccessAccountPermissions.Write |
SharedAccessAccountPermissions.List,
Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
ResourceTypes = SharedAccessAccountResourceTypes.Service,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
Protocols = SharedAccessProtocol.HttpsOnly
};
return storageAccount.GetSharedAccessSignature(policy);
要了解更多信息,请参考MSDoc。
英文:
Thanks to Peter Csala
for the comments.
>To combine the two functions, you need to modify the return type of the GetUserDelegationSasBlobwithcontent() function to return the content of the blob file as a string or byte array. Then you can call this function inside the Run() function and pass the SAS token as a parameter to the GetUserDelegationSasBlobwithcontent() function.
To integrate the two functions into one, you can modify the GetUserDelegationSasBlobwithcontent
function to return the contents of the blob file.
And you can call this function in the SasTokenFunction
and return the result to the client app.
string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);
public static async Task<string> GetUserDelegationSasBlobwithcontent(string sasToken)
{
.
.
}
The below namespaces need to be used in the code.
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Azure.Storage.Blobs;
using Azure.Identity;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
I used the code and able to fetch the token.
public static class Function1
{
[FunctionName("SasTokenFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("samplecontainer");
SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
};
string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";
string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);
return (ActionResult)new OkObjectResult(sasUriToken);
}
public static async Task<string> GetUserDelegationSasBlobwithcontent(string sasToken)
{
string storageAccountUriString = $"https://formsample5.blob.core.windows.net";
var credential = new DefaultAzureCredential();
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample"); //container name
BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");
Uri blobUri = new Uri(blobClient.Uri + "?" + sasToken);
BlobClient sasBlobClient = new BlobClient(blobUri);
BlobDownloadInfo download = sasBlobClient.Download();
var content = download.Content;
using (var streamReader = new StreamReader(content))
{
string blobContent = await streamReader.ReadToEndAsync();
return blobContent;
}
}
}
Token generation
Sample code to fetch the SAS token.
const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=<storage-account>;AccountKey=<account-key>";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
Permissions = SharedAccessAccountPermissions.Read |
SharedAccessAccountPermissions.Write |
SharedAccessAccountPermissions.List,
Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
ResourceTypes = SharedAccessAccountResourceTypes.Service,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
Protocols = SharedAccessProtocol.HttpsOnly
};
return storageAccount.GetSharedAccessSignature(policy);
For further information on this, refer to MSDoc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论