Try for free Book a demo

Creating Azure Service Principal Using Graph Client

Microsoft Azure

6 Mins Read | Last modified on July 30th, 2024

This blog will brief on how to create a service principal using graph client. Whenever you register an Azure Active Directory application in the Azure Portal, two objects will be created in your Azure Active Directory tenant, an application object and a service principal object.

Introduction

An Azure Active Directory application is identified by a unique application object, which would reside in the registered Azure Active Directory tenant. To access resources that are secured by an Azure AD tenant, the entity that requires access must be represented by a security principal. This is true for both users (user principal) and also applications (service principal). The security principal defines the access policy and furthermore, permissions for the user/application in the Azure AD tenant.

This enables core features such as authentication of the user/application during sign-in, and also authorization during resource access.

When an application is given permission to access resources in a tenant, a service principal object is created. Service principal is an identity, which your application can use to log in and also access the Azure resources.

Prerequisites

Before creating an Azure Active Directory, application and service principal using the graph client you must create a native Active Directory Application. The Native Application should exist in the tenant where the Service Principal should be created. This can be created through the Azure portal.

Prerequesties

Make sure to provide the delegated permission, ‘access the directory as the signed-in user’ to the native application created. When you create an Azure Active Directory application you need either delegate permission or application permission. Note down the application id of this native app to use in the program.

Azure Service Principal

To create the service principal, this native application will act as an agent. The client ID of the native app which you have granted delegate permission will be used at the time of Azure Active Directory application creation from the program.

Follow the steps below to create Azure Service Principal using Graph client

    1. Create a Console App
      • Launch Visual Studio and also create a new Console App project.
    2. Add the NuGet Packages
      • Right-click the newly created project and also select Manage NuGet Packages.
      • Click the Browsetab, search for Azure.ActiveDirectory.GraphClient.
      • Click Install to complete the installation. 
    3. In Program.cs, add the following using statements at the top of the namespace definition, before the class declaration. This would enable using the included NuGet package in the program
      • using Microsoft.Azure.ActiveDirectory.GraphClient;
      • using Microsoft.IdentityModel.Clients.ActiveDirectory;
    4. Within the Program class, declare the following variables and also initialize with appropriate values. Set the nativeAppId variable with the Application Id obtained while creating the native application in the Azure portal.Set tenantId with the Tenant Id of the Azure Active Directory in your subscription.Set the username and also userPassword as the Azure portal Username and Password of the account with access to the mentioned tentantId. graphResourceId can be the same as mentioned below.
    const string nativeAppId = "Native Application Id";

    const string tenantId = "Tenant Id";

    const string graphResourceId = "https://graph.windows.net";

    const string username = "Username";

    const string userPassword = "Password";
    1. Add the following GetAccessToken() method within the class. This acquires the access token for accessing the graph client using native application Id and user credentials.
public static async Task<string> GetAccessToken(string userName, string password)

   {

            var context = new       AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));

            var tokenResponse = await context.AcquireTokenAsync("https://graph.windows.net",         nativeAppId, new UserCredential(userName, password));

            var accessToken = tokenResponse.AccessToken;

            return accessToken;

   }

Main Method

In the main() method add the following,

    1. Initialize the active directory client with your tenantId and user credentials.
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, 
async () => await GetAccessToken(username, userPasswrod));
    1. Now we shall create an active directory application object. This should hold necessary information like homepage url, display name and identifier uri’s. These are the details we would be providing when we create an Active Directory application in the Azure Portal.
Application application = new Application

{

      Homepage = "http://localhost:4200/",

      DisplayName = "Application Display name",

      IdentifierUris = new List<string> { "http://localhost/" }

};
    1. All the necessary steps for creating the Active Directory application is done. Below is the code that can create the application.
activeDirectoryClient.Applications.Active DirectorydApplicationAsync(application).GetAwaiter().GetResult();

Create Azure Service Principal

    1.   First get the created application by its name in the program
var azureADApplications = activeDirectoryClient.Applications.ExecuteAsync().GetAwaiter().GetResult();
var app = azureADApplications.CurrentPage.FirstOrDefault(r => r.DisplayName.Equals("Application Display name"));
    1. Create service principal object with Active Directory application’s Id
 ServicePrincipal servicePrincipal = new ServicePrincipal

 {

        AppId = app.AppId

 };

    1. Create the service principal using the following line
activeDirectoryClient.ServicePrincipals.Active DirectorydServicePrincipalAsync(servicePrincipal).GetAwaiter().GetResult();

Program.cs

This is how your whole Program.cs file should look like,

class Program

    {

        public static async Task<string> GetAccessToken(string userName, string password)

        {

            var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));

            var tokenResponse = await context.AcquireTokenAsync("https://graph.windows.net", nativeAppId, new UserCredential(userName, password));

            var accessToken = tokenResponse.AccessToken;

            return accessToken;

        }

 

        const string nativeAppId = "Native Application Id";

        const string tenantId = "Tenant Id";

        const string graphResourceId = "https://graph.windows.net";

        const string username = "Username";

        const string userPasswrod = "Password";

 

        static void Main(string[] args)

        {

            Uri servicePointUri = new Uri(graphResourceId);

            Uri serviceRoot = new Uri(servicePointUri, tenantId);

            ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetAccessToken(username, userPasswrod));

            Application application = new Application

            {

                Homepage = "http://localhost:4200/",

                DisplayName = "Application Display name",

                IdentifierUris = new List<string> { "http://localhost/" }

            };           

               activeDirectoryClient.Applications.Active DirectorydApplicationAsync(application).GetAwaiter().GetResult();

 

            var azureADApplications = activeDirectoryClient.Applications.ExecuteAsync().GetAwaiter().GetResult();

            var app = azureADApplications.CurrentPage.FirstOrDefault(r => r.DisplayName.Equals("Application Display name"));

 

            ServicePrincipal servicePrincipal = new ServicePrincipal

            {

                AppId = app.AppId

            };

            activeDirectoryClient.ServicePrincipals.Active DirectorydServicePrincipalAsync(servicePrincipal).GetAwaiter().GetResult();           

        }

    }

Run the program with necessary details. Find the Active Directory app (Service Principal) created in Azure Active Directory under App registrations in the Azure portal.

Azure Service Principal

Conclusion

Service Principals are service accounts in Azure. The Authorization hierarchy works top to bottom which means – if you’re authorizing someone to access a top-level resource, the authorization will be passed down to every resource under the top-level resource. For example – if you authorize a Service Principal to access a Resource Group – all the resources inside the Resource Group will be accessible.

This article was originally published on Jan 17, 2019. It was most recently updated on Jul 30, 2024.

Advanced Cloud Management Platform - Request Demo CTA

Related Articles