如何使用postman为Azure文件存储调用REST API?

时间:2017-07-18 06:01:49

标签: java rest azure logic postman

我想通过邮递员调用与天蓝色文件存储相关的REST API。 以下是我提出要求的方式:

enter image description here

我正在请求列出文件存储帐户中的所有共享,如下所述:https://docs.microsoft.com/en-us/rest/api/storageservices/list-shares

我收到以下错误:

  

"请求中的Date标头不正确。"   我应该做些什么改变?

Edit1:

当我提供正确格式的日期时,我有这样的错误:

enter image description here

我收到以下错误: "在HTTP请求中找到的MAC签名''与任何计算签名不同。服务器使用以下字符串进行签名:' GET"

如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

使用更新的屏幕截图,您的问题似乎与x-ms-date不再相关。 出现403错误的原因是Header中的Authorization属性格式为

  

授权=" [SharedKey | SharedKeyLite] [AccountName]:[签名]"

您不应该直接使用Azure门户上的访问密钥作为授权签名部分,而应该构建它 使用UTF-8编码的 HMAC-SHA256 算法编码请求字符串。 格式为

  

签名= Base64的(HMAC-SHA256(UTF8(StringToSign)))

official document上提及。

示例java代码如下所示,介绍如何构建授权的签名部分:

String stringToSign = "GET\n" 
       + "\n" // content encoding
       + "\n" // content language
       + "\n" // content length
       + "\n" // content md5
       + "\n" // content type
       + "\n" // date
       + "\n" // if modified since
       + "\n" // if match
       + "\n" // if none match
       + "\n" // if unmodified since
       + "\n" // range
       + "x-ms-date:" + date + "\nx-ms-version:2015-02-21\n" // headers
       + "/" + <your account name> + "/"+"\ncomp:list"; // resources
       String auth = getAuthenticationString(stringToSign);

private static String getAuthenticationString(String stringToSign) throws Exception {
       Mac mac = Mac.getInstance("HmacSHA256");
       mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
       String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
       String auth = "SharedKey " + account + ":" + authKey;
       return auth;
}

代码中的auth参数是根据上面提到的签名生成的,然后您可以在授权属性中填写它并在Postman中重新发送请求。

截图如下: enter image description here

重要提示:

在上面的代码中,你不应该错过&#34; \ n comp:list&#34;在//资源行中,否则它也会返回403错误。 您可以在Constructing the Canonicalized Resource String

中找到规则

答案 1 :(得分:1)

您指向的链接就是这个例子:

PUT http://myaccount/mycontainer?restype=container&timeout=30 HTTP/1.1  
x-ms-version: 2015-02-21  
x-ms-date: Fri, 26 Jun 2015 23:39:12 GMT  
Authorization: SharedKey myaccount:ctzMq410TV3wS7upTBcunJTDLEJwMAZuFPfr0mrrA08=  
Content-Length: 0  

您使用的日期格式不正确:

  

所有经过身份验证的请求都必须包含请求的协调世界时(UTC)时间戳。您可以在x-ms-date标头或标准HTTP / HTTPS Date标头中指定时间戳。如果在请求中指定了两个标头,则x-ms-date的值将用作请求的创建时间。

修改
在授权标题上,链接文章中的Authentication for the Azure Storage Services链接指出以下内容:

  

要对请求进行身份验证,您必须使用发出请求的帐户的密钥对请求进行签名,并将该签名作为请求的一部分传递。

     

Authorization标题的格式如下:
  Authorization =“[SharedKey | SharedKeyLite]:”
  其中SharedKeySharedKeyLite是授权方案的名称,AccountName是请求资源的帐户的名称,Signature是基于哈希的消息验证代码( HMAC)根据请求构造并使用SHA256算法计算,然后使用Base64编码进行编码。

以下是Hash-based Message Authentication Code (HMAC)

的更多信息

您评论过:

  

嗨,密钥与我的azure portal帐户的“访问密钥”标签中提供的密钥相同。你的建议是什么?

这就是问题所在。您不应该使用密钥作为邮件的Signature,您需要计算基于密钥的Signature

简而言之:

  • 使用“访问密钥”标签中的密钥
  • 计算请求的SHA256哈希值
  • Base64编码SHA256哈希输出
  • 使用Base64编码的字符串作为Signature