Tuesday, December 24, 2019

.NET Code for Obtaining an Azure AD Bearer Token

Source: Azure Blog
Azure AD provides great ways to connect applications and worker roles so that they can be secured to outside while easily communicated with inside. Service principles are a great way to ensure the applications within the same subscription are communicating security. But you can claim a security token and communicate with the other applications that are hosted internally.

For example, imagine you have a publicly exposed API that gets you some data output. Now you need to secure the API such that only applications authorized via Azure AD is granted with data access.

You can simply secure this with the [Authorize] tag at either controller or the output HTTP method level. Also on the Api end, at the Startup.cs file's ConfigureService method you need to add Azure AD authorization with the following code.



services.AddAuthentication(sharedOptions =>
{
      sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(options => Configuration.Bind("AzureAdAuth", options));

This means you are configuring authorizing via the Bearer token.

Now, in the application you are calling this endpoint you need to use the following code for obtaining a bearer token.

HttpClient httpClient = new HttpClient();
AuthenticationContext authContext =
                new AuthenticationContext('https://login.microsoftonline.com/'+<TenantID>, false);

ClientCredential clientCredential =
                new ClientCredential(<ClientID>, <ClientSecret>);
AuthenticationResult result =
                await authContext.AcquireTokenAsync(<ClientID>, clientCredential);
 return result.AccessToken;

The three parameters required are the TenantID, which is at the Azure AD level. Then the Client ID and Client Secret from an app registration of the Azure AD.

Happy Coding....

1 comment:

  1. Each business is different and requires customized options which match their own brand and identification. web design firms for ad agencies

    ReplyDelete