如何生成sas令牌并使用它将文件上载到azure blob存储?

5ssjco0h  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(392)

我正在生成一个azure sas令牌,以便像这样将文件上载到azure

// create client
    val storageConnectionString = s"DefaultEndpointsProtocol=https;AccountName=${accountName};AccountKey=${accountKey}"
    val storageAccount = CloudStorageAccount.parse(storageConnectionString)
    val client = storageAccount.createCloudBlobClient()
    // get blob client
    val container = client.getContainerReference(containerName)
    val blockBlob = container.getBlockBlobReference(path)
    // generate SAS token
    val policy = new SharedAccessBlobPolicy()
    policy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.CREATE, SharedAccessBlobPermissions.WRITE))
    val now = new Date()
    val calendar = Calendar.getInstance()
    calendar.setTime(now)
    calendar.add(Calendar.DATE, -1)
    val start = calendar.getTime
    calendar.add(Calendar.HOUR, 10)
    val end = calendar.getTime
    policy.setSharedAccessStartTime(start)
    policy.setSharedAccessExpiryTime(end)
    val token = blockBlob.generateSharedAccessSignature(policy, null)

上面的逻辑输出是这样的

sig=XXXXXXXXXXXXXXX&st=2020-09-04T00%3A13%3A56Z&se=2020-09-04T10%3A13%3A56Z&sv=2019-02-02&spr=https&sp=cw&sr=b

现在我试着把这个令牌添加到 Authorization 上传文件的put请求中的头

$ curl -X PUT -H 'Accept: */*' -H 'Content-Type: application/json' -H 'Authorization: SharedAccessSignature sig=XXXXXXXXXXXXXXX&st=2020-09-04T00%3A13%3A56Z&se=2020-09-04T10%3A13%3A56Z&sv=2019-02-02&spr=https&sp=cw&sr=b' -d '{}' https://<AccountName>.blob.core.windows.net/<ContainerName>/test.json -v

但这样做失败了


* upload completely sent off: 8 out of 8 bytes

< HTTP/1.1 403 Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
< Content-Length: 321
< Content-Type: application/xml
< Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
< x-ms-request-id: f5fd7e6b-601e-0058-681b-837a50000000
< Date: Sat, 05 Sep 2020 00:30:47 GMT
< 
<?xml version="1.0" encoding="utf-8"?>
<Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:f5fd7e6b-601e-0058-681b-837a50000000

* Connection #0 to host <AccountName>.blob.core.windows.net left intact

Time:2020-09-05T00:30:47.9553766Z</Message></Error>* Closing connection 0

我的相依关系 build.sbt :

lazy val azureLibs = Seq(
  "com.azure" % "azure-storage-blob" % "12.7.0",
  "com.microsoft.azure" % "azure-storage" % "8.6.5"
)

如何正确生成sas令牌并使用它将文件上载到azure blob存储?

pcww981p

pcww981p1#

我将解决方案总结如下。
如果我们想使用共享访问签名(sas令牌)来管理azure blob,我们需要使用sas令牌作为查询字符串。所以请求url应该是 https://<AccountName>.blob.core.windows.net/<ContainerName>/test.json?<your sas token> . 详情请参阅此处

相关问题