如何验证从 ASP.NET 核心中的 Microsoft Teams 发送的消息负载?

How to verify the message payload sent from Microsoft Teams in ASP.NET core?

我按照这里的示例代码 enter link description here 来验证请求有效负载,但它在我的 asp.net 核心项目中不起作用,看起来它适用于传统的 ASP.NET 项目。如何在 asp.net 核心中做到这一点?

几个月前我在一个ASP.NET核心项目中写了一个函数,你可以看看下面的代码。

public TeamsAuthResponse Validate(HttpRequest request)
{
    request.Body.Seek(0, SeekOrigin.Begin);
    string messageContent = new StreamReader(request.Body).ReadToEnd();
    var authenticationHeaderValue = request.Headers["Authorization"];

    if (authenticationHeaderValue.Count <= 0)
    {
        return new TeamsAuthResponse(false, "Authentication header not present on request.");
    }

    if (!authenticationHeaderValue[0].StartsWith("HMAC"))
    {
        return new TeamsAuthResponse(false, "Incorrect authorization header scheme.");
    }

    // Reject all empty messages
    if (string.IsNullOrEmpty(messageContent))
    {
        return new TeamsAuthResponse(false, "Unable to validate authentication header for messages with empty body.");
    }

    string providedHmacValue = authenticationHeaderValue[0].Substring("HMAC".Length).Trim();
    string calculatedHmacValue = null;
    try
    {
        byte[] serializedPayloadBytes = Encoding.UTF8.GetBytes(messageContent);
        byte[] keyBytes = Convert.FromBase64String(_securityToken);
        using (HMACSHA256 hmacSHA256 = new HMACSHA256(keyBytes))
        {
            byte[] hashBytes = hmacSHA256.ComputeHash(serializedPayloadBytes);
            calculatedHmacValue = Convert.ToBase64String(hashBytes);
        }

        if (string.Equals(providedHmacValue, calculatedHmacValue))
        {
            return new TeamsAuthResponse(true, null);
        }
        else
        {
            string errorMessage = string.Format(
                "AuthHeaderValueMismatch. Expected:'{0}' Provided:'{1}'",
                calculatedHmacValue,
                providedHmacValue);
            return new TeamsAuthResponse(false, errorMessage);
        }
    }
    catch (Exception ex)
    {
        _logger.LogWarning(ex, "Exception occcured while verifying HMAC on the incoming request.");
        return new TeamsAuthResponse(false, "Exception thrown while verifying MAC on incoming request.");
    }
}