Getting AAD token with silent login

Sometimes devops need their apps to perform some operation as a human, such as stopping a virtual machine when monitoring system alarms, as traditional ways of azure authorization such as management certificates or profile file  grant too much permission and may cause security risks, ARM and RBAC is quite recommended to fully organize and control access to azure resources. see more details about ARM/RBAC: https://azure.microsoft.com/en-us/documentation/articles/role-based-access-control-configure/

So in devops app, silent login usually happens, which means the app acts as a human to get AAD token by silent login and then perform subsequent operation against Azure platform.

here is how to get AAD token by silent login in China Azure.

string _aadTenantDomain = ConfigurationManager.AppSettings[“_aadTenantDomain”];
            //_aadTenantDomain = “yourdomain.partner.onmschina.cn”;
            string _aadClientId = ConfigurationManager.AppSettings[“_aadClientId”]; //the app should be registered first in the target AAD, the client ID can be found right at app info under the AAD

            AuthenticationResult result = null;
            var context = new AuthenticationContext(“https://login.chinacloudapi.cn/” + _aadTenantDomain);

            // Directly specify the username and password.
            var credential = new UserCredential(
                ConfigurationManager.AppSettings[“CoAdminUser”],
                ConfigurationManager.AppSettings[“CoAdminPassword”]);
            result = context.AcquireToken(
                “https://management.core.chinacloudapi.cn/”,
                _aadClientId,
                    credential);
            if (result == null)
            {
                throw new InvalidOperationException(“Failed to obtain the JWT token”);
            }
            string token = result.AccessToken;

Here is to get all resource groups with the token

string _subscriptionId = ConfigurationManager.AppSettings[“azureSubscriptionID”];
var client = new HttpClient();
var header = token;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, header);

try
{
var result = await client.GetStringAsync(
String.Format(
“https://management.chinacloudapi.cn/subscriptions/{0}/resourcegroups?api-version=2015-01-01”,
_subscriptionId));

more about ARM REST APIs: https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *