上一篇文章 [Azure][C#] 取得 AppService 中的 Application Settings 並且更改值 ,我們提到了再 Azure 上面產生權限,並且讀寫 AppService 上面的 App
Settings ,但是上一篇文章有一個不大不小的問題,就是押出的憑證權限太大了,幾乎可以對自己的服務摧枯拉朽,這點我們家 DevOps 不悅了,所以我大概研究一下如何押出有權限的憑證..
首先,我們先登入 Azure 點選上方的 console
接下來輸入指令
az ad sp create-for-rbac --name "APPNAME 這邊我的測試專案是 monacolab" --role contributor --scopes /subscriptions/你的SUBSCRIPTIONS ID/resourceGroups/
你的RESOURCEGROUP ID
之後跑一下後他就會給你以下的資訊
{
"appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"displayName": "monacolab",
"name": "http://monacolab",
"password": "passWordPassWord.passWordPassword~PaSsSs",
"tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
這時候你就拿到了 appId , password , tenant ,這時候我們來測試一下,這邊測試的方式是,我會用一個該憑證有權限控制的 appservice 我來取得他的 appid ,之後我再去存取一個是我的 appservice 但是沒有權限看看會怎樣
記得撰寫前不要忘記下載套件
https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent/ ,
https://www.nuget.org/packages/Microsoft.Azure.Management.ResourceManager.Fluent/
Console.WriteLine("Hello World!");
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
"appidxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"PAsswordPassword.PAsswordPassword~Pass",
"tenantxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", AzureEnvironment.AzureGlobalCloud);
//建立實體,載入憑證
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
//這是可控制的 app service
//format : /subscriptions/[Subscription ID]/resourceGroups/[Resource group]/providers/Microsoft.Web/sites/[APP SERVICENAME]
var correctAppId = "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/FREE-PLAN-LAB/providers/Microsoft.Web/sites/monacolab";
var webAppCorrect =
azure.AppServices.WebApps.GetById(correctAppId);
Console.WriteLine(webAppCorrect.Id);
Console.WriteLine("\r\n\r\n============= SPLIT =============\r\n\r\n");
var errorAppId = "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/FREE-SERVICE-EASE-ASIA/providers/Microsoft.Web/sites/geekcalendar";
var webAppWrong=
azure.AppServices.WebApps.GetById(errorAppId);
Console.WriteLine(webAppWrong.Id);
果然在沒有權限的時候 發生了 Exception
這樣就達到我們家 DevOps 要的效果了,不多說了,我先去找他吵架..
reference :
https://markheath.net/post/create-service-principal-azure-cli