gpt4 book ai didi

azure - 将 ClaimsPrincipal 从 Azure Function 传递到 BlobClient

转载 作者:行者123 更新时间:2023-12-03 03:21:25 25 4
gpt4 key购买 nike

我正在创建一个 Azure Function 作为“中间件”,以便最终用户直接在浏览器中打开 Azure Blob 存储中的文件。我使用 AAD 来保护 Azure Function,并创建 SAS url/ token 来访问 blob。到目前为止,一切都很好。但是,我想使用 ACL、添加用户和/或组来控制 blob 容器的安全性。因此,我想连接到 Blob 容器,而不是使用 Azure Function 的标识,而是使用登录用户的标识。

如何将登录用户“传递”到 Blob 连接,这样我只能在用户有权访问的情况下创建 SAS token ?

enter image description here

最佳答案

您可以在 HttpTrigger 函数中使用 DefaultAzureCredential 中的以下代码:-

HttpTrigger 函数:-

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Security.Claims;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

namespace FunctionApp40
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log,
ClaimsPrincipal claimIdentity)
{
string endpoint = "https://<StorageAccountName>.blob.core.windows.net";
DefaultAzureCredential credential = new DefaultAzureCredential();
BlobServiceClient blobServiceClient = new BlobServiceClient(
new Uri(endpoint), credential);

// Get the user's identity
string userName = claimIdentity.Identity.Name;
log.LogInformation($"User name: {userName}");

// Add BlobContainerClient
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("<container-name>");

// Get the access policy for the container
BlobContainerAccessPolicy accessPolicy = await containerClient.GetAccessPolicyAsync();

// Check if the user has access to the blob container
bool hasAccess = false;
foreach (BlobSignedIdentifier identifier in accessPolicy.SignedIdentifiers)
{
if (identifier.Id == userName)
{
hasAccess = true;
break;
}
}

if (hasAccess)
{
// Create a SAS token with the appropriate permissions
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = "test",
Resource = "c",
ExpiresOn = DateTimeOffset.UtcNow.AddHours(1),
Protocol = SasProtocol.Https
};
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);

// Use the SAS token to create a BlobServiceClient object
string sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential("<StorageAccount-name>", "<Account-Key>")).ToString();
BlobServiceClient sasClient = new BlobServiceClient(new Uri($"https://<StorageAccountName>.blob.core.windows.net?{sasToken}"));

// You can use the 'sasClient' to access the container with the SAS token.
// Example: BlobContainerClient sasContainerClient = sasClient.GetBlobContainerClient("<container-name>");

// Return something meaningful, such as the SAS token or a success message
return new OkObjectResult($"SAS Token: {sasToken}");
}

// If the user doesn't have access, return a Forbidden status
return new StatusCodeResult(StatusCodes.Status403Forbidden);
}
}
}

输出:-

enter image description here

另一个用于检索 SAS token 的 HttpTrigger C# 代码:-

using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Azure.Storage.Blobs;
using Azure.Identity;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.WindowsAzure.Storage;
using System.Threading.Tasks;

namespace FunctionApp40
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string accountName = "valleystrg98"; // Replace with your storage account name
string sasToken = GetAccountSASToken(accountName);

return new OkObjectResult(sasToken);
}

private static string GetAccountSASToken(string accountName)
{
// Replace with your actual account settings
const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=valleystrg98;AccountKey=xxxxkxxxxvtVn7AxxxxL+AStdZzGlQ==";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

// Create a new access policy for the account.
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 the SAS token.
return storageAccount.GetSharedAccessSignature(policy);
}
}
}

enter image description here

浏览器:-

enter image description here

关于azure - 将 ClaimsPrincipal 从 Azure Function 传递到 BlobClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77202174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com