Slack文档中的This example 使用的是表单url编码的正文,但是Slack Events Api发送的是json。我尝试使用C#加密名称空间实现示例中的伪代码。无法获得匹配的签名。
当我在C#中检查请求正文时,它包括对引号(")字符的转义,我非常确定当请求正文在松弛端被散列时,这些字符不在请求正文中。我如何知道我的请求正文的原始版本与Slack用来创建散列的请求正文相匹配?我使用HMACSHA256的方式有问题吗?我查看了this,但没有找到任何可以推断到C#的东西。
{
...
string signingKey = ConfigurationManager.AppSettings["Slack:SigningSecret"].ToString();
string timestamp = GetHeaderValue(actionContext, "X-Slack-Request-Timestamp");
string SlackSignature = GetHeaderValue(actionContext, "X-Slack-Signature");
var app = HttpContext.Current;
string requestBody = string.Empty;
using (var stream = new MemoryStream())
{
app.Request.InputStream.Seek(0, SeekOrigin.Begin);
app.Request.InputStream.CopyTo(stream);
requestBody = Encoding.UTF8.GetString(stream.ToArray());
app.Request.InputStream.Seek(0, SeekOrigin.Begin);
}
string sig_basestring = "v0:" + timestamp + ":" + requestBody;
var hmac256 = HMACSHA256.Create();
hmac256.Key = Encoding.ASCII.GetBytes(signingKey);
var sig_hash =
hmac256.ComputeHash(Encoding.ASCII.GetBytes(sig_basestring));
var computedSignature = "v0=" + ToHex(sig_hash, false);
bool isValidRequest = SlackSignature.Equals(computedSignature);
if (!isValidRequest)
{
throw new HttpResponseException(HttpStatusCode.Forbidden);
}
...
}
private string ToHex(byte[] bytes, bool upperCase)
{
var result = new StringBuilder(bytes.Length * 2)
for (int i = 0; i < bytes.Length; i++)
result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));
return result.ToString();
}发布于 2021-10-23 17:45:10
我偶然发现了SlackNet,并找到了可行的解决方案:
var encoding = new UTF8Encoding();
using (var hmac = new HMACSHA256(encoding.GetBytes(signingSecret)))
{
var hash = hmac.ComputeHash(encoding.GetBytes($"v0:{timestamp}:{requestBody}"));
var hashString = $"v0={BitConverter.ToString(hash).Replace("-", "").ToLower(CultureInfo.InvariantCulture)}";
if (hashString.Equals(SlackSignature)) return continuation();
}
...https://stackoverflow.com/questions/69589150
复制相似问题