如何验证来自 Slack Events API 的请求

5 http-post node.js express slack-api

我正在使用validate-slack-request包来验证传入的 slack 请求是否来自 slack。这对于斜杠命令和交互组件(按钮等)来说效果很好。但是它不适用于事件 API

我注意到事件 API 的 POST 请求正文具有不同的格式。没有payload. 但我不清楚什么是松弛让我可以用来验证。代码如下

//This WORKS
app.post("/interactiveCommand", async (req, res) => {
  const legit = validateSlackRequest(process.env.SLACK_SIGNING_SECRET, req, false);
  if (!legit) {
    console.log("UNAUTHORIZED ACCESS ", req.headers, req.body);
    return res.status(403).send("Unauthorized");
  }
  await interactiveCommand(...);
  return;
});

//This does NOT WORK
app.post("/slackEvents", parser, json, async (req, res) => {
  const legit = validateSlackRequest(process.env.SLACK_SIGNING_SECRET, req, false);
  if (!legit) {
    console.log("UNAUTHORIZED ACCESS ", req.headers, req.body);
    res.status(403).send("Unauthorized");
  } else {
    try {
      switch (req.body.event.type) {
        case "message":
          await handleMessageEvent(...);
          break;
        case "app_home_opened":
          res.status(200).send();
          await updateUserHomePage(...);
          break;
        default:
          res.status(200).send();
          return;
      }
    } catch(e) {
      console.log("Error with event handling! ", e);
    }
  }
});

const crypto = require('crypto')
const querystring = require('querystring')

// Adhering to RFC 3986
// Inspired from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
function fixedEncodeURIComponent (str) {
  return str.replace(/[!'()*~]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  })
}

/**
 * Validate incoming Slack request
 *
 * @param {string} slackAppSigningSecret - Slack application signing secret
 * @param {object} httpReq - Express request object
 * @param {boolean} [logging=false] - Enable logging to console
 *
 * @returns {boolean} Result of vlaidation
 */
function validateSlackRequest (slackAppSigningSecret, httpReq, logging) {
  logging = logging || false
  if (typeof logging !== 'boolean') {
    throw new Error('Invalid type for logging. Provided ' + typeof logging + ', expected boolean')
  }
  if (!slackAppSigningSecret || typeof slackAppSigningSecret !== 'string' || slackAppSigningSecret === '') {
    throw new Error('Invalid slack app signing secret')
  }
  const xSlackRequestTimeStamp = httpReq.get('X-Slack-Request-Timestamp')
  const SlackSignature = httpReq.get('X-Slack-Signature')
  const bodyPayload = fixedEncodeURIComponent(querystring.stringify(httpReq.body).replace(/%20/g, '+')) // Fix for #1
  if (!(xSlackRequestTimeStamp && SlackSignature && bodyPayload)) {
    if (logging) { console.log('Missing part in Slack\'s request') }
    return false
  }
  const baseString = 'v0:' + xSlackRequestTimeStamp + ':' + bodyPayload
  const hash = 'v0=' + crypto.createHmac('sha256', slackAppSigningSecret)
    .update(baseString)
    .digest('hex')

  if (logging) {
    console.log('Slack verifcation:\n Request body: ' + bodyPayload + '\n Calculated Hash: ' + hash + '\n Slack-Signature: ' + SlackSignature)
  }
  return (SlackSignature === hash)
}
Run Code Online (Sandbox Code Playgroud)

小智 1

这就是我让它发挥作用的方法,这是一些尝试和错误,我不做任何承诺。基本上,如果我要验证事件而不是斜杠命令或交互式组件,我将传递type="Event"给验证函数。唯一的变化是我如何根据传入请求构造有效负载

export function validateSlackRequest(
  slackAppSigningSecret,
  httpReq,
  logging,
  type = ""
) {
  logging = logging || false;
  if (typeof logging !== "boolean") {
    throw new Error(
      "Invalid type for logging. Provided " +
        typeof logging +
        ", expected boolean"
    );
  }
  if (
    !slackAppSigningSecret ||
    typeof slackAppSigningSecret !== "string" ||
    slackAppSigningSecret === ""
  ) {
    throw new Error("Invalid slack app signing secret");
  }
  const xSlackRequestTimeStamp = httpReq.get("X-Slack-Request-Timestamp");
  const SlackSignature = httpReq.get("X-Slack-Signature");
  let bodyPayload;
  if (type === "Event") {
    bodyPayload = (httpReq as any).rawBody;
  } else {
    bodyPayload = fixedEncodeURIComponent(
      querystring.stringify(httpReq.body).replace(/%20/g, "+")
    ); // Fix for #1
  }
  if (!(xSlackRequestTimeStamp && SlackSignature && bodyPayload)) {
    if (logging) {
      console.log("Missing part in Slack's request");
    }
    return false;
  }
  const baseString = "v0:" + xSlackRequestTimeStamp + ":" + bodyPayload;
  const hash =
    "v0=" +
    crypto
      .createHmac("sha256", slackAppSigningSecret)
      .update(baseString)
      .digest("hex");

  if (logging) {
    console.log(
      "Slack verification:\nTimestamp: " +
        xSlackRequestTimeStamp +
        "\n Request body: " +
        bodyPayload +
        "\n Calculated Hash: " +
        hash +
        "\n Slack-Signature: " +
        SlackSignature
    );
  }
  return SlackSignature === hash;
}
Run Code Online (Sandbox Code Playgroud)