Windows Azure Active Directoryで認証して管理API(Azure Service Management API)を呼んだりするための備忘録。
ライブラリは以下が必要です。
NuGet Gallery | Active Directory Authentication Library 2.14.201151115
AADには、アプリの登録とユーザーの追加 (xxxx@yyyonmicrosoft.com 的) を行っておきます。例によってCredentialをプログラム上から行う場合、組織アカウントの必要あります。
参考:
以下、LINQPadでのコード例ですので、VSで実行するときは、適宜修正を。ざっくり説明すると、ADで認証してTokenをゲッツして、そのあとManagement APIを呼び出してサブスクリプション一覧を取得しています。
void Main() { var tenantId = "テナントID"; var clientId = "クラアントID"; var organizationAccount = "組織アカウント"; var password = "パスワード"; string token = GetAuthorizationHeader(tenantId, clientId, organizationAccount, password); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); client.DefaultRequestHeaders.Add("x-ms-version", "2013-08-01"); var uri = new UriBuilder("https://management.core.windows.net/subscriptions"); uri.Uri.Dump(); var response = client.GetAsync(uri.Uri).Result; response.Content.ReadAsStringAsync().Result.Dump(); } private string GetAuthorizationHeader(string tenantId, string clientId, string organizationAccount, string password) { var context = new AuthenticationContext( "https://login.windows.net/" + tenantId + "/"); var user = new UserCredential(organizationAccount, password); var result = context.AcquireTokenAsync( "https://management.core.windows.net/", clientId, user).Result; if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return result.AccessToken; }