Created
October 4, 2019 23:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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