Skip to content

Instantly share code, notes, and snippets.

@PeterKottas
Last active August 29, 2019 20:45
  • Select an option

Select an option

Revisions

  1. PeterKottas revised this gist Aug 29, 2019. 1 changed file with 12 additions and 0 deletions.
    12 changes: 12 additions & 0 deletions Impala webhook verification - dot net core
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,15 @@
    public static class ImpalaHeaderContants
    {
    public const string XImpalaSignature = "X-Impala-Signature";
    }

    public class ImpalaConfigDTO
    {
    public string ApiKey { get; set; }

    public string WebhookSecret { get; set; }
    }

    public class ImpalaWebhookVerificationAttribute : ActionFilterAttribute
    {
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  2. PeterKottas created this gist Aug 29, 2019.
    38 changes: 38 additions & 0 deletions Impala webhook verification - dot net core
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    public class ImpalaWebhookVerificationAttribute : ActionFilterAttribute
    {
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
    var config = context.HttpContext.RequestServices.GetService<IOptionsSnapshot<ImpalaConfigDTO>>().Value;
    var strContent = await context.HttpContext.Request.GetRawBodyStringAsync();
    context.HttpContext.Request.Headers.TryGetValue(ImpalaHeaderContants.XImpalaSignature, out var headers);
    var xImpalaSignature = headers.FirstOrDefault();
    var actualXImpalaSignature = GetXImpalaSignature(strContent, config.WebhookSecret);
    if (actualXImpalaSignature != xImpalaSignature)
    {
    var logger = context.HttpContext.RequestServices.GetService<ILogger<ImpalaWebhookVerificationAttribute>>();
    logger.LogWarning(string.Format("Unverified webhook call Body=[{0}] Hash=[{1}]", strContent, xImpalaSignature));
    context.Result = (context.Controller as Controller).StatusCode(403);
    }
    else
    {
    await next();
    }
    }

    private static string GetXImpalaSignature(string text, string key)
    {
    ASCIIEncoding encoding = new ASCIIEncoding();

    var textBytes = encoding.GetBytes(text);
    var keyBytes = encoding.GetBytes(key);

    byte[] hashBytes;

    using (HMACSHA256 hash = new HMACSHA256(keyBytes))
    {
    hashBytes = hash.ComputeHash(textBytes);
    }

    return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }
    }