Created
September 3, 2020 16:05
-
-
Save snobu/fda372845b5faf3908c9a5a50f674297 to your computer and use it in GitHub Desktop.
Call remote API from Azure Function with Managed Identity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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