Skip to content

Instantly share code, notes, and snippets.

@snobu
Created September 3, 2020 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snobu/fda372845b5faf3908c9a5a50f674297 to your computer and use it in GitHub Desktop.
Save snobu/fda372845b5faf3908c9a5a50f674297 to your computer and use it in GitHub Desktop.
Call remote API from Azure Function with Managed Identity
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Azure.Identity;
using Microsoft.Azure.Services.AppAuthentication;
using System.Net.Http;
namespace lighthousefunc
{
public static class HttpTrigger
{
[FunctionName("HttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string audience = "https://management.azure.com";
//var token = new DefaultAzureCredential();
AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider();
string accessToken = await tokenProvider.GetAccessTokenAsync(audience);
log.LogInformation($"Successfully acquired access token from Managed Identity: {accessToken.Substring(0,10)}");
// We have the access token let's call ARM API
try
{
string targetAPI = "https://management.azure.com/subscriptions?api-version=2020-01-01";
HttpClient c = new HttpClient();
c.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
string response = await c.GetStringAsync(targetAPI);
return new OkObjectResult(response);
}
catch (Exception ex)
{
log.LogError($"Error calling remote REST API: {ex.Message}");
return new BadRequestObjectResult($"Function called the remote REST API but response was not success: {ex.Message}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment