-
-
Save dajor/a901044d55caa3b56cd12ac59b44e554 to your computer and use it in GitHub Desktop.
Azure Cosmos DB + Functions Cookbook —secure access run.csx
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
#r "Microsoft.Azure.Documents.Client" | |
using Microsoft.Azure.Documents; | |
using Microsoft.Azure.Documents.Client; | |
using System.Net; | |
using System.Configuration; | |
using Microsoft.Azure.KeyVault; | |
using Microsoft.Azure.Services.AppAuthentication; | |
private static HttpClient httpClient = new HttpClient(); | |
private static DocumentClient client = null; | |
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) | |
{ | |
string id = req.GetQueryNameValuePairs() | |
.FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0) | |
.Value; | |
if (string.IsNullOrEmpty(id)){ | |
return req.CreateResponse(HttpStatusCode.BadRequest); | |
} | |
if(client == null){ | |
client = await GetSecureDocumentClient(); | |
} | |
Uri documentUri = UriFactory.CreateDocumentUri("your database","your collection",id); | |
Document doc = await client.ReadDocumentAsync(documentUri); | |
if (doc == null){ | |
return req.CreateResponse(HttpStatusCode.NotFound); | |
} | |
return req.CreateResponse(HttpStatusCode.OK, doc); | |
} | |
private static async Task<DocumentClient> GetSecureDocumentClient() | |
{ | |
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); | |
string endpointUrl = ConfigurationManager.AppSettings["cosmosDBAccountEndpoint"]; | |
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback), httpClient); | |
var key = await keyVaultClient.GetSecretAsync(ConfigurationManager.AppSettings["keyVaultAccessUri"]); | |
return new DocumentClient(new Uri(endpointUrl), key.Value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment