2022-08-16

[Azure] C# 透過 Microsoft.Azure.Management.Fluent 取得 Azure Storage (Table) 的操作事件

這篇主要目的是因為有朋友問,如何得知 Azure Table 中資料被存取,其實我有跟他說過你可以透過 在入口網站 左邊的 共用存取簽章 Shared Access Signature (SAS)

來做到控管




而且,其實也可以透過左邊網路的部份去限制 IP 


但是朋友希望可以看到這 storage 裡面的所有 Event Log 這時候就稍微麻煩點



1. 你要取得 權限 請參考這篇文章

https://blog.no2don.com/2020/09/azurec-c-azure.html

指令:

az ad sp create-for-rbac --name "PORJECTNAME" --role contributor --scopes /subscriptions/abcdefgh-1234-4321-5678-abcdefabcdef/resourceGroups/GROUP_NAME/providers/Microsoft.Storage/storageAccounts/STORAGENAME


2.下載套件

Microsoft.Azure.Management.Fluent

Microsoft.Azure.Management.ResourceManager.Fluent


3.接下來就是把步驟一的資料包含 clientId=appId , clientSecret=password , tenantId=tenant

var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal( clientId, clientSecret, tenatId, AzureEnvironment.AzureGlobalCloud); var azure = Microsoft.Azure.Management.Fluent.Azure.Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); var logs = azure.ActivityLogs.DefineQuery() .StartingFrom(DateTime.Now.AddHours(-24)) .EndsBefore(DateTime.Now) .WithAllPropertiesInResponse() .FilterByResource("/subscriptions/SUBSCRIPTIONID/resourceGroups/RESOURCENAME/providers/Microsoft.Storage/storageAccounts/STORAGENAME") .Execute(); Console.WriteLine("Check Traffic Manager Activity Logs : "); var i = 0; foreach (var eventLog in logs) { Console.WriteLine("時間: " + eventLog.EventTimestamp.Value.ToString("yyyy-MM-dd HH:mm:ss")); string json = JsonConvert.SerializeObject(eventLog, Formatting.Indented); Console.WriteLine(json); Console.WriteLine("--------"); }


結果:


這樣你就可以透過程式的方法去拿到log 拿到你要的資訊。

--

The bug existed in all possible states. Until I ran the code.

如果這篇文章有幫助到您幫我分享一下,讓我有寫下去的動力...