Search code examples
c#azureservice-management

Connect to the Azure Service Management API from c#, without the interactive login


I am trying to connect to the Azure Service Management APi, using C#, but the only way the example (https://msdn.microsoft.com/en-gb/library/azure/ee460782.aspx) works if through an interactive authentication method, requiring me to enter my Azure username and password. As we will want to call this method from within a worker role, this won't be possible. Is there a way of doing this?


Solution

  • As we will want to call this method from within a worker role, this won't be possible. Is there a way of doing this?

    There are two ways of doing it:

    1. Connect to your Azure Subscription using X509 Certificate: Though not recommended based on the direction in which Azure is going but it is an option.
    2. Create a user in Azure AD just for executing Service Management API: In this approach what you will do is create a user in your Azure AD. Then you will assign this user a Co-Admin role in your Azure Subscription (both of them should be done through old Azure Portal). Once you do that, you would need to get the token by specifying the username/password in your code. Something like below:

          var authContext = new AuthenticationContext("https://login.microsoftonline.com/{tenantid}")
          UserCredential userCredential = new UserCredential(userName, password);
          AuthenticationResult authResult = authContext.AcquireToken("https://management.core.windows.net/", clientId, userCredential);
      

    However, please keep in mind a few things:

    • If you're creating the user through Azure Portal, make sure you sign in at least once using that user as in this case user is required to change the password on 1st login. Also please ensure that the user's password doesn't expire. I believe using Graph API directly you can achieve these.
    • Putting user credentials in the code has some big risks. If someone gets hold of this username/password, they essentially get access to your entire subscription.

    If possible, please see if using Azure Resource Manager (ARM) API is an option for you for managing your subscription instead of Service Management API. With Role-based access control (RBAC) in ARM API, you can simply create a Service Principal type user and grant them only the permissions they need. No need to make them a co-admin on your subscription.