【问题标题】:HMAC authorization for Faraday法拉第的 HMAC 授权
【发布时间】:2021-10-31 15:44:32
【问题描述】:

我正在为 API 创建一个 ruby​​ 包装器,但他们似乎使用了 Faraday 不支持的某种奇怪的授权,所以看来我必须创建自己的函数来生成它.他们的网站上有这个

您的 API 凭证包含一个公共客户端标识符 (UUIDv4) 和一个密钥(32 字节,交付 base64 编码)。组织级别的请求身份验证使用 Amazon 样式的 HMAC 完成

还有这个

Content-MD5: base64(md5(body)), RFC 1864 (binary md5)
Content-Type: 'application/json'
Date: 'Mon, 07 Dec 2015 22:57:52 +0200' (RFC 2822)
Authorization: 'Success ' + client_identifier + ':' +
    base64(
      sha512_hmac( // returned as binary
        join(
          '\n', // unix newline, not the 2 character string
          [
            http_verb,    // 'POST' / 'GET' / etc.
            Content-MD5,  // Same as header above. Include even for empty string body.
            Content-Type, // Same as header above. Can be empty.
            Date,         // Same as header above.
            http_path     // '/api/v1/document/?foo=bar'
          ]
        ),
        key // in binary, remember to decode base64
      )
    )

现在我已经设法构建了一个非常混乱的函数,如下所示

def create_authorization_header(path, payload)
    date = Date.today.rfc2822            
    md5_file = Digest::MD5.hexdigest(payload)
    content_md5 = Base64.strict_encode64(md5_file)
    digest = OpenSSL::Digest.new('sha512')                
    autorization_header = "GET " + content_md5 + " application/json " + date + path
    autorization_header_enc =  'Success '+ identifier + ':' + Base64.strict_encode64(OpenSSL::HMAC.digest(digest, api_key, autorization_header))
    connection.headers['Authorization'] = autorization_header_enc
    connection.headers['Content-MD5'] = content_md5
    connection.headers['Content-type'] = "application/json"     
    connection.headers['Date'] = date       
end

但这似乎不起作用,我找不到我缺少的东西。关于这里可能有什么问题的任何建议?

【问题讨论】:

    标签: ruby api faraday


    【解决方案1】:

    您将autorization_header 的大部分内容用空格作为分隔符连接起来。根据python示例代码,它们都应该用换行符分隔。你可以改用这样的东西:

    autorization_header = ["GET", content_md5, "application/json", date, path].join("\n")
    

    此外,您的content_md5 使用 MD5 哈希的 base64 编码十六进制编码输出。但是,您应该使用 md5 哈希的 base64 编码原始二进制输出,即

    md5_file = Digest::MD5.digest(payload)
    

    最后,date 应该是当前时间戳,即

    date = Time.now.rfc2822
    

    可能还有更多问题,但这是我现在发现的。在实现这样的协议时,您必须确保完全遵循编码要求和哈希格式。否则,数据将不匹配。您应该尝试找到一个有效请求的示例并尝试构建您的实现,以便它能够重新创建这个确切的请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 2021-10-12
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2022-11-10
      • 2013-05-03
      相关资源
      最近更新 更多