![](/img/trans.png)
[英]Hadoop Azure: Issue when authenticating storage account using MSI in App Service Plan (Azure Functions)
[英]Authenticating Azure Storage with system assigned Identity from Azure Functions
我想使用來自 Azure 函數的系統分配標識來驗證和讀取存儲帳戶。 我得到了 .NET 的以下代碼。 我在 Java 中尋找等效代碼。 提前致謝。
public static class Function1
{
[FunctionName("WebHook-Func")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/");
TokenCredential creds = new TokenCredential(accessToken);
log.LogInformation($"Token: {accessToken}");
StorageCredentials storageCreds = new StorageCredentials(creds);
try
{
CloudBlobClient client = new CloudBlobClient(new StorageUri(new Uri("https://<storageAccount>.blob.core.windows.net")), storageCreds);
CloudBlobContainer container = client.GetContainerReference("fltd");
CloudBlockBlob blob = container.GetBlockBlobReference("shopping.txt");
string content = await blob.DownloadTextAsync();
return (ActionResult)new OkObjectResult($"File contents: {content}");
}catch(Exception ex)
{
return new BadRequestObjectResult($"Exception when calling web hook: {ex.StackTrace} {ex.Message}");
}
}
}
如果要使用系統分配的身份訪問 Azure function 中的 Azure blob,請參考以下步驟
Sdk
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-client-authentication</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>8.6.5</version>
</dependency>
public HttpResponseMessage run(@HttpTrigger(name = "req",methods = {HttpMethod.GET, HttpMethod.POST},authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request, ExecutionContext context) throws URISyntaxException, StorageException, IOException {
context.getLogger().info("Java HTTP trigger processed a request.");
AppServiceMSICredentials msiCredentials = new AppServiceMSICredentials(AzureEnvironment.AZURE);
String token = msiCredentials.getToken("https://storage.azure.com/");
context.getLogger().info("000000000000" + token);
String accountName = "jimtestdiag924";
StorageCredentialsToken credentials = new StorageCredentialsToken(accountName, token);
CloudStorageAccount account = new CloudStorageAccount(credentials, true);
CloudBlobClient client = account.createCloudBlobClient();
CloudBlobContainer container = client.getContainerReference("testupload");
CloudBlockBlob blob = container.getBlockBlobReference("hello.txt");
String content = blob.downloadText();
return request.createResponseBuilder(HttpStatus.OK).body("The file content :" + content).build();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.