[英]How to generate a SAS token and use it to upload a file to Azure Blob Storage?
我正在生成一个 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
现在我尝试将此令牌添加到 PUT 请求中的Authorization
标头以上传文件
$ 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
依赖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 存储?
我总结了以下解决方案。
如果我们想使用共享访问签名(SAS 令牌)来管理 Azure blob,我们需要使用 SAS 令牌作为查询字符串。 所以请求 url 应该像https://<AccountName>.blob.core.windows.net/<ContainerName>/test.json?<your sas token>
。 欲知更多详情,请参阅此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.