예제 #1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string token = string.Empty;

            log.LogInformation("GenerateBearerToken Function is called");

            try
            {
                string  resourceUri = req.Query["ResourceUri"];
                string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                resourceUri = resourceUri ?? data?.ResourceUri;

                if (!string.IsNullOrEmpty(resourceUri))
                {
                    log.LogInformation("Fetching details from KeyVault");
                    //Fetching UAMI Client Id and Tenant Id from Key Vaults
                    string clientId_UAMI = await KeyVaultHelper.FetchKeyVaultSecret(ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.clientId_UAMI), log);

                    string tenantId = await KeyVaultHelper.FetchKeyVaultSecret(ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.tenantId), log);

                    token = await TokenHelper.GetToken(clientId_UAMI, tenantId, resourceUri, log);


                    if (!string.IsNullOrEmpty(token))
                    {
                        return(new OkObjectResult("Bearer " + token));
                    }
                    else
                    {
                        return(new OkObjectResult("[Error] Exception has been occured in generating token.Please check Function logs under Monitor"));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult("[Warning] Resource Uri is missing in request"));
                }
            }
            catch (Exception ex)
            {
                return(new NotFoundObjectResult($"\n GenerateBearerToken got an exception \n Time: { DateTime.Now} \n Exception{ ex.Message}"));
            }
        }
예제 #2
0
        /// <summary>
        /// To fetch secret from Key Vault
        /// </summary>
        /// <param name="secretName"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public static async Task <string> FetchKeyVaultSecret(string secretName, ILogger log)
        {
            string value = string.Empty;

            try
            {
                using (var client = new HttpClient())
                {
                    //Invoking FetchSecretFromKeyVaultAPI to fetch secret value
                    string Uri = ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.FetchSecretFromKeyVaultAPI) + secretName;

                    if (Uri.Contains("azure-api.net"))
                    {
                        //Adding subscription key header to the request
                        client.DefaultRequestHeaders.Add(ConstantsHelper.ocp_Apim_Subscription_Key, ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.ocp_Apim_Subscription_Key));
                    }
                    //Get response
                    var response = await client.GetAsync(Uri).ConfigureAwait(false);

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        value = await response.Content.ReadAsStringAsync();

                        log.LogInformation("Fetched secret value from key vault");
                        return(value);
                    }
                    else
                    {
                        log.LogInformation("FetchKeyVaultSecret is failed with status code : " + response.StatusCode);
                        return(value);
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogInformation($"CreateBearerTokenV3 got \n Exception Time: {DateTime.Now} \n Exception{ ex.Message}");
                return(value);
            }
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
            ILogger log)
        {
            try
            {
                log.LogInformation("PushLogsToLogAnalytics Function Called");
                //Get Request Data
                dynamic data = await req.Content.ReadAsAsync <object>();

                string customLogFile  = data.LogFileName;
                string automationName = data.AutomationName;
                string moduleName     = data.ModuleName;
                string logData        = Convert.ToString(data.LogData);

                //Parsing provided logData Json
                JObject logDataObj  = JObject.Parse(logData);
                string  logDataJson = logDataObj.ToString(Newtonsoft.Json.Formatting.Indented);

                //Preparing Final Json for Log Analytics Injection
                dynamic obj = new JObject();
                obj.AutomationName = automationName;
                obj.ModuleName     = moduleName;
                obj.Log            = logDataJson;
                string myJson = obj.ToString(Newtonsoft.Json.Formatting.Indented);
                log.LogInformation("PreparedFinalJson : " + myJson);

                //Validating Json - User provided Log Data Json and prepared final Json
                bool isChildJsonValid  = LogAnalyticsHelper.IsValidJson(logDataJson, log);
                bool isParentJsonValid = LogAnalyticsHelper.IsValidJson(myJson, log);

                if (isChildJsonValid && isParentJsonValid)
                {
                    log.LogInformation("Fetching details from KeyVault");
                    log.LogInformation("Invoking FetchKeyVaultSecret method");
                    string workspaceId = await KeyVaultHelper.FetchKeyVaultSecret(ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.logAnalyticsWorkspaceID), log);

                    string primaryKey = await KeyVaultHelper.FetchKeyVaultSecret(ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.logAnalyticsWorkspaceSharedKey), log);

                    log.LogInformation("FetchKeyVaultSecret executed successfully");

                    //Invoking PushLogsToLogAnalytics method to ingest the logs into workspace
                    bool status = await LogAnalyticsHelper.PushLogsToLogAnalytics(myJson, customLogFile, workspaceId, primaryKey, log);

                    if (status)
                    {
                        log.LogInformation("Ingestion of log analytics is completed.");
                        return(req.CreateResponse(HttpStatusCode.OK, "[Info] Ingestion of log analytics is completed."));
                    }
                    else
                    {
                        log.LogInformation("Ingestion of log analytics is failed");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, "[Error] Ingestion of log analytics is failed"));
                    }
                }
                else
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, $"[Warning] Invalid Json Provided"));
                }
            }
            catch (System.Exception ex)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound, $"{ex.Message}"));
            }
        }
예제 #4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string secretValue = string.Empty;

            log.LogInformation("GetKeyVaultSecret Function is called");

            try
            {
                //Get secret Name from the query string
                string  secretName  = req.Query["SecretName"];
                string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                secretName = secretName ?? data?.SecretName;

                if (!string.IsNullOrEmpty(secretName))
                {
                    log.LogInformation("Secret Vaule Requested For : " + secretName);

                    //Create new service token provider using System Assigned Managed Identity
                    AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

                    //Create new Key Vault Client
                    KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

                    //Get Key Vault Name from application configuration
                    string keyVaultName = ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.keyVaultName);
                    log.LogInformation("Fetching Details from KeyVault : " + keyVaultName);

                    //Fetching the Key Vault URI
                    string keyVaultUri = String.Format(Convert.ToString(ConstantsHelper.keyVaultUri), keyVaultName);
                    log.LogInformation("KeyVaultUri : " + keyVaultUri);

                    //Get secret from Key Vault
                    SecretBundle secretBundle = await keyVaultClient.GetSecretAsync(keyVaultUri, secretName);

                    if (secretBundle != null)
                    {
                        //Get Secret Value to be returned
                        secretValue = secretBundle.Value;
                        log.LogInformation("Details are fetched from KeyVault");
                        return(new OkObjectResult(secretValue));
                    }
                    else
                    {
                        log.LogInformation("No such key name present in KeyVault");
                        //Return no key found message
                        return(new NotFoundObjectResult("No such key name present in KeyVault"));
                    }
                }
                else
                {
                    log.LogInformation("secretName is missing in request");
                    return(new BadRequestObjectResult("secretName is missing in request"));
                }
            }
            catch (Exception ex)
            {
                log.LogInformation($"GetKeyVaultSecret got an exception \n Time: { DateTime.Now} \n Exception{ ex.Message}");
                return(new NotFoundObjectResult($"\n GetKeyVaultSecret got an exception \n Time: { DateTime.Now} \n Exception{ ex.Message}"));
            }
        }