Securing API-to-API Azure App Services Using Managed Identity

  1. Configure a Managed Identity for the Core Application
[HttpGet]
2public async Task<ActionResult<string>> GetAsync([FromQuery] int auth = 1)
3{
4 try
5 {
6 var httpClient = new HttpClient();
7
8 // Allow authorization to be bypassed to compare with/without a valid
9 // access token
10 if (auth == 1)
11 {
12 // Requires the Azure.Identity package
13 //
14 // DefaultAzureCredential will return a credential appropriate to
15 // the environment in which this app is running. For an Azure app
16 // service with a managed identity configured, the credential will
17 // reflect that identity.
18 var azureCredential = new DefaultAzureCredential();
19
20 // The TokenRequestContext specifies the target app for which a
21 // token based on the Azure credential is being requested. Here
22 // it's the integration API app's default scope.
23 var context = new TokenRequestContext(
24 new string[] { "https://your-integrationapi-url.azurewebsites.net/.default" });
25
26 // Azure provides a behind-the-scenes means within the app service
27 // environment to obtain an access token.
28 var token = await azureCredential.GetTokenAsync(context);
29
30 // Specify the access token in the Authorization header
31 httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
32 }
33
34 // The actual request to the secured "integration" API
35 var result = await httpClient.GetStringAsync(
36 "https://your-integrationapi-url.azurewebsites.net/integration");
37
38 return Ok($"Call to 'API' succeeded. Response from 'Integration': {result}");
39 }
40 catch (Exception e)
41 {
42 return StatusCode(500, $"Exception: {e.Message}\n\nStack trace:\n{e.StackTrace}");
43 }
44}
  1. Instantiate a DefaultAzureCredential object
  2. Create a TokenRequestContext, specifying the scope for the target service, in this case the integration API
  3. Invoke the GetTokenAsync method on the DefaultAzureCredential object, passing the TokenRequestContext
  4. Use the resulting token (token.Token) to form an Authorization header for the request to the integration API

-Donnie Hale, Product Development Team Lead AWH. We are helping companies fuel growth through technology.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
AWH

AWH

318 Followers

We help companies fuel growth through technology. Connect with us at awh.net