Azure Active Directory – Native app – Step by step

In continuation of my previous blog – Register an app with the Azure Active Directory v2.0 endpoint – demonstrating how to create an Application Type: Native app within Azure.

Create a Native app

    • Step 1: Create
        1. Login to portal.azure.com
        2. Go to Azure Active Directory > App registrations > New Application Registration
        3. In the Name field, give a descriptive name
        4. Choose Native
        5. For Sign-on Url: Here it doesn’t matter – give http://localhost:12345
        6. Click on Create.
    • Step 2: Configure
        1. Once the App is created, click on Settings
        2. Please note that here there is no way to set a Key as a Client Secret – why? the explanation is given on the difference between Native app & Web app
        3. Under Required permissions, based on all available API, set all necessary permissions you need to, please note here that after settings up permissions, you/AAD Admin need to “Grant” them explicitly otherwise, it will not work.
    • Step 3: Take Note
        1. Application ID – which is the Client ID
        2. Tenant ID => Azure Active Directory > Properties > Directory ID

Native App – Usage

Here the code is straightforward:

A. Get Access Token

public static string GetAccessToken()
        {
            string AppId = "";
            string TenantId = "";
            string GraphResourceUrl = "https://graph.microsoft.com";
            string AuthorityUrl = "https://login.microsoftonline.com/" + TenantId;
            string RedirectUri = "http://localhost:12345/";

            try
            {
                AuthenticationContext authContext = new AuthenticationContext(AuthorityUrl, true);
                AuthenticationResult authResult = authContext.AcquireTokenAsync(GraphResourceUrl, AppId, new Uri(RedirectUri), new PlatformParameters(PromptBehavior.Auto)).Result;
                return authResult.AccessToken;

            }
            catch (Exception ex)
            {
            }
            return null;
        }
B. Get GraphServiceClient

public static GraphServiceClient GetGraphClient(string graphToken)
        {
            try
            {
                DelegateAuthenticationProvider authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                    return Task.FromResult(0);
                });
                return new GraphServiceClient(authenticationProvider);
            }
            catch (Exception ex)
            {
            }
            return null;
        }