如何在ASP.NET Core中验证从Microsoft Teams发送的消息有效负载?

时间:2018-07-30 09:13:09

标签: microsoft-teams

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

1 个答案:

答案 0 :(得分:2)

几个月前,我在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.");
    }
}