Skip to content

Instantly share code, notes, and snippets.

@jeffhollan
Last active November 23, 2017 04:30
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 jeffhollan/65934fd4c71f0f2a39169ab92c1bae3b to your computer and use it in GitHub Desktop.
Save jeffhollan/65934fd4c71f0f2a39169ab92c1bae3b to your computer and use it in GitHub Desktop.
Azure Funciton Service Principal
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