mailersend / mailersend-nodejs

The official MailerSend Node.js SDK
https://developers.mailersend.com
MIT License
125 stars 17 forks source link

Add a code sample to verify a webhook signature #89

Open Agathe-Brusset opened 6 months ago

Agathe-Brusset commented 6 months ago

We have information on how to verify a signature in PHP but do not provide more code examples, please provide one and share here so we can publish it to the dev docs.

davidsbond commented 1 month ago

Here's how I did it for Go:

package webhook

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "io"
    "net/http"
)

func Handle(w http.ResponseWriter, r *http.Request) {
    hash := hmac.New(sha256.New, []byte("<WEBHOOK_SECRET>"))
    body := bytes.NewBuffer(nil)
    reader := http.MaxBytesReader(r.Body, http.DefaultMaxHeaderBytes)

    // Use io.MultiWriter so you can decode the request payload using the "body" variable
    // once the signature is validated.
    if _, err := io.Copy(io.MultiWriter(hash, payload), reader); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    if hex.EncodeToString(hash.Sum(nil)) != r.Header.Get("Signature") {
        http.Error(w, "invalid signature", http.StatusForbidden)
        return
    }
}

I had to reverse engineer it a bit using the PHP example so it would be good to have it documented.