C# example of validating webhook signature

Apologies if this is the wrong category.

Does anyone have a published working example of validating webhook signature in C# please?

I’m building out some external provisioning logic in Azure Functions and have not yet cracked the signature validation.

I’ve read this topic by @promofaux which pointed me at checking correct encoding and operating at byte level, but I haven’t sorted it yet.

Unfortunately I need to focus on our business logic so switching off validation for now. As and when I do resolve it I’d be happy to post a gist, but in the meantime if anyone could point me at an existing example I’d really appreciate it.

Julian

Hi @Julian_Elve,

So I have a method for validating the signature as follows:

https://github.com/PromoFaux/Matterhook.NET/blob/master/Matterhook.NET/Code/Util.cs#L13-L44

You could probably simplify it a little to work specifically for Discourse webhooks, but I use it for both Discourse and Github hooks, so needed to be able to change out the sha<x>= part at the beginning.

For Discourse, it’s used like so:

https://github.com/PromoFaux/Matterhook.NET/blob/master/Matterhook.NET/Controllers/DiscourseHookController.cs#L79

Hope that helps some…!

9 Likes

thanks so much @PromoFaux !

Updated - now have this working in production - thanks again Adam. (Bizarrely can’t make my local manual tests work, which is almost certain to be something to do with copy and paste of request body from the Discourse log into Postman… :thinking:

@Falco I see you moved this from support to dev - no problem as far as I am concerned of course, but I read the description of the dev category and it seems to be development of Discourse rather than the services around it, hence choosing support :smile:

4 Likes

Bizarrely can’t make my local manual tests work

You may find it useful to stick a Console.WriteLine() as an else to if (signature == calcSig) . Something like

Console.WriteLine($"Calculated Signature: {calcSig}\nSignature from webhook: {signature}");

Keep in mind that when you are sending test hooks using Postman, you need to change the signature header value if you make any changes to the actual payload. When testing I would run it through my app, let it fail, and then just copy/paste the calculated signature into the header :wink:

1 Like