Skip to content

Commit

Permalink
Also validate signature for challenge request when cresting webhooks. (
Browse files Browse the repository at this point in the history
  • Loading branch information
bexxx authored Sep 1, 2020
1 parent 219a394 commit 84c6ddb
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions samples/batch/csharp/webhookreceiver/webhookreceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,21 @@ public static async Task<IActionResult> Run(
return new BadRequestErrorMessageResult(message);
}

if (eventKind == WebHookEventKind.Challenge)
{
var validationToken = request.Query[ValidationTokenKeyQueryParameterName].FirstOrDefault();
logger.LogInformation("Received challenge and responded.");

return new OkObjectResult(validationToken);
}

logger.LogInformation($"Received web hook notification, kind={eventKindString}");

string requestBody = await new StreamReader(request.Body).ReadToEndAsync();

string requestBody = null, validationToken = null, payload;
if (headers.TryGetValue(WebHookSignatureHeaderName, out var actualSignature))
{
var contentBytes = Encoding.UTF8.GetBytes(requestBody);
if (eventKind == WebHookEventKind.Challenge)
{
validationToken = request.Query[ValidationTokenKeyQueryParameterName].FirstOrDefault();
payload = validationToken;
}
else
{
requestBody = await new StreamReader(request.Body).ReadToEndAsync();
payload = requestBody;
}

var contentBytes = Encoding.UTF8.GetBytes(payload);
var secretBytes = Encoding.UTF8.GetBytes(Program.WebHookSecret);
using (var hmacsha256 = new HMACSHA256(secretBytes))
{
Expand All @@ -78,6 +78,15 @@ public static async Task<IActionResult> Run(
}
}

if (eventKind == WebHookEventKind.Challenge)
{
logger.LogInformation("Received challenge and responded.");

return new OkObjectResult(validationToken);
}

logger.LogInformation($"Received web hook notification, kind={eventKindString}");

var webHookNotification = JsonConvert.DeserializeObject<WebHookNotification>(requestBody);

// invocationId can be used for deduplication, it's unique per notification event
Expand Down

0 comments on commit 84c6ddb

Please sign in to comment.