Skip to content

Instantly share code, notes, and snippets.

@retgits
Created October 4, 2019 23:47
Show Gist options
  • Save retgits/8d541f203020a089fd0970e29c471958 to your computer and use it in GitHub Desktop.
Save retgits/8d541f203020a089fd0970e29c471958 to your computer and use it in GitHub Desktop.
A quick snippet for a Gin middleware to validate whether messages actually come from Slack
// Complete workflow from: https://api.slack.com/docs/verifying-requests-from-slack
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
const (
// See https://api.slack.com/docs/verifying-requests-from-slack#signing_secrets_admin_page
// on how to get the Slack signing secret for your API
signingSecret = "MySlackSigningSecret"
)
func SlackAuthenticator() gin.HandlerFunc {
return func(c *gin.Context) {
buf := new(bytes.Buffer)
buf.ReadFrom(c.Request.Body)
slackRawBody := buf.String()
slackTimestamp := c.GetHeader("X-Slack-Request-Timestamp")
i, err := strconv.ParseInt(slackTimestamp, 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
hash := hmac.New(sha256.New, []byte(signingSecret))
hash.Write([]byte(fmt.Sprintf("v0:%s:%s", slackTimestamp, slackRawBody)))
hexits := fmt.Sprintf("v0=%s", hex.EncodeToString(hash.Sum(nil)))
slackSignature := c.GetHeader("X-Slack-Signature")
if slackSignature == hexits {
c.Set("X-Valid-Slack-Message", true)
} else {
c.Set("X-Valid-Slack-Message", false)
}
fmt.Println(hexits)
c.Next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment