Last active
November 23, 2017 04:30
-
-
Save jeffhollan/65934fd4c71f0f2a39169ab92c1bae3b to your computer and use it in GitHub Desktop.
Azure Funciton Service Principal
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.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
using Microsoft.Azure.WebJobs; | |
using Microsoft.Azure.WebJobs.Extensions.Http; | |
using Microsoft.Azure.WebJobs.Host; | |
using Newtonsoft.Json.Linq; | |
using Microsoft.Azure.Services.AppAuthentication; | |
using Microsoft.Azure.KeyVault; | |
using Microsoft.Azure.EventHubs; | |
using System.Text; | |
using System; | |
namespace ScaleTestV1_NoHost | |
{ | |
public static class Http | |
{ | |
// I'm using a static HttpClient and EventHubClient so that | |
// multiple function executions within a single function app | |
// instance don't have to initialize new resources every execution. | |
private static HttpClient client = new HttpClient(); | |
private static EventHubClient eventHubClient; | |
[FunctionName("MyFunction")] | |
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log) | |
{ | |
log.Info("C# HTTP trigger function processed a request."); | |
// So I don't have to call key vault every execution, I only retrieve the secret | |
// if I don't already have the client initialized. This way invoking my function 1000 | |
// times doesn't result in 1000 calls to key vault which would get throttled. | |
if(eventHubClient == null) | |
{ | |
log.Info("Retrieving secret from keyvault"); | |
// This is the part where I grab the secret. | |
var azureServiceTokenProvider = new AzureServiceTokenProvider(); | |
var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback), client); | |
string eventHubConnectionString = (await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("EventHubSecretId"))).Value; | |
// And now I use the secret to create an Event Hub Client | |
eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString); | |
} | |
// Do some work here | |
// Send to Event Hub via my key-vaulted connection string client | |
await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message.ToString()))); | |
log.Info($"Sent message to Event Hub"); | |
return req.CreateResponse(HttpStatusCode.OK, message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment