邮递员-在预请求脚本中访问完整的请求正文(以计算哈希)

Mis*_*siu 5 javascript c# security postman

我正在尝试在PostMan中重新创建C#DelegatingHandler。
我创建了用于计算auth标头值的请求前脚本。

目前,我的脚本如下所示:

function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1); 
}

function GetNonce() {
    return (S4() + S4() + S4()+ S4() + S4() + S4() + S4()+ S4()).toLowerCase();
}

function GetTimeStamp() {
    var d = new Date();
    return Math.round(d.getTime() / 1000);
}

function getAuthHeader(httpMethod, requestUrl, requestBody) {
    var CLIENT_KEY = postman.getEnvironmentVariable('hmac_user');
    var SECRET_KEY = postman.getEnvironmentVariable('hmac_key');
    var AUTH_TYPE = 'HMAC';

    requestUrl = requestUrl.replace(/{{(\w*)}}/g,function(str,key) {return environment[key]});
    requestUrl = requestUrl.toLowerCase();
    var requestTimeStamp = GetTimeStamp();
    var nonce = GetNonce();
    var bodyHash="";

    if (httpMethod == 'GET' || !requestBody) {
        requestBody = ''; 
    } else {
        var md5 = CryptoJS.MD5(requestBody);
        bodyHash = CryptoJS.enc.Base64.stringify(md5);
    }  

    var signatureRawData = [CLIENT_KEY, requestUrl, httpMethod, requestTimeStamp, nonce, bodyHash].join("");

    var key = CryptoJS.enc.Base64.parse(SECRET_KEY);
    var hash = CryptoJS.HmacSHA512(signatureRawData, key);
    var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

    var header = [CLIENT_KEY, hashInBase64, nonce, requestTimeStamp].join(":");

    return AUTH_TYPE+" "+header;
}

postman.setEnvironmentVariable('hmacAuthHeader', getAuthHeader(request.method, request.url, request.data));
Run Code Online (Sandbox Code Playgroud)

对于没有任何正文的GET请求,此方法非常理想。但是,当我发送x-www-form-urlencoded请求时,由于C#和Postman内部的正文哈希差异,我得到未经授权的响应(401)。

Postman内部request.data是一个JSON对象,但是当我在Fiddler中调查请求时,我看到它是作为字符串发送的(请参见下面的屏幕截图) 在此处输入图片说明

我发送邮件时也会发生同样的事情form-data。在邮递员内部,我添加了3个字段,一个带有字符串值,两个带有文件。在Fiddler中,我可以看到完整的请求,但是在Postman中,我无法访问这些文件(请参见下面的屏幕截图) 在此处输入图片说明

我正在尝试访问完整的请求正文,因为我需要从中计算出哈希值。

我在C#中有可用的代码,不是我想用Postman重新创建相同的请求。

我的问题是:
如何在请求前脚本中访问完整的请求正文?

我在C#中使用此代码,它工作正常:

internal class HmacClientHandler : DelegatingHandler
{
    private readonly string _applicationId;
    private readonly string _applicationKey;

    public HmacClientHandler(string appId, string appKey)
    {
        _applicationId = appId;
        _applicationKey = appKey;
    }

    protected override async Task<HttpResponseMessage>SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
    {
        HttpResponseMessage response = null;
        string url = Uri.EscapeUriString(request.RequestUri.ToString().ToLowerInvariant());
        string methodName = request.Method.Method;

        DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan timeSpan = DateTime.UtcNow - epochStart;
        string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
        string nonce = Guid.NewGuid().ToString("N");

        string contentBase64String = string.Empty;

        if (request.Content != null)
        {
            byte[] content = await request.Content.ReadAsByteArrayAsync();
            MD5 md5 = MD5.Create();
            byte[] hash = md5.ComputeHash(content);
            contentBase64String = Convert.ToBase64String(hash);
        }

        string authenticationKeyString = string.Format("{0}{1}{2}{3}{4}{5}", _applicationId, url, methodName, requestTimeStamp, nonce, contentBase64String);
        var secretKeyBase64ByteArray = Convert.FromBase64String(_applicationKey);

        using (HMACSHA512 hmac = new HMACSHA512(secretKeyBase64ByteArray))
        {
            byte[] authenticationKeyBytes = Encoding.UTF8.GetBytes(authenticationKeyString);
            byte[] authenticationHash = hmac.ComputeHash(authenticationKeyBytes);
            string hashedBase64String = Convert.ToBase64String(authenticationHash);
            request.Headers.Authorization = new AuthenticationHeaderValue("HMAC", string.Format("{0}:{1}:{2}:{3}", _applicationId, hashedBase64String, nonce, requestTimeStamp));
        }

        response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

前面引用的问题 (#1050) 似乎仅适用于二进制/文件模式 ( RequestBody.MODES.file) 的请求正文。该RequestBodyAPI 提供了我需要的类似用例: https ://www.postmanlabs.com/postman-collection/RequestBody.html

我相信,如果您pm.request.body在预请求脚本中引用,它将提供您正在寻找的内容。具体来说,pm.request.body.toString()似乎提供了x-www-url-encoded最终出现在请求中的实际字符串(尽管,如果您在请求参数中使用环境变量,这些变量将无法解析,例如,{{variable_name}})。

因此,对于上面的脚本,我将最后一行更改为:

postman.setEnvironmentVariable('hmacAuthHeader', getAuthHeader(request.method, request.url, pm.request.body.toString()));
Run Code Online (Sandbox Code Playgroud)

...这似乎提供了一个合理的 HMAC。请务必注意哈希/HMAC 协议的所有规则,包括参数排序、空格处理等。

另外,我不确定该RequestBodyAPI 是否在 Postman 的所有版本中都可用,但在我的本机 Windows 和 OS X 版本上运行良好。希望这可以帮助!