gpt4 book ai didi

java - 使用服务主体验证存储帐户

转载 作者:行者123 更新时间:2023-12-02 01:50:32 27 4
gpt4 key购买 nike

在java中,我想使用服务主体(首选使用客户端证书)进行身份验证,以从blobstorage写入/读取文件。

我开始使用 StorageAccount 和访问 key ,但我需要更细粒度的权限控制(例如仅限于读取或写入)。

我在 azure 文档中找不到任何有关如何执行此操作的示例,也没有在代码中找到任何入口点。

最佳答案

根据我的研究,Azure 不提供build-in role它仅具有 Blob 存储资源的读/写权限。所以我们需要create a custom role根据您的需要。然后您可以将角色分配给服务主体。关于创建自定义角色,请引用以下步骤

  1. 定义角色 json

    {
    "Name": "Azure blob Writer",
    "Id": null,
    "IsCustom": true,
    "Description": "Read and write blob",
    "Actions": [
    "Microsoft.Storage/storageAccounts/blobServices/containers/read",
    "Microsoft.Storage/storageAccounts/blobServices/containers/write",
    "Microsoft.Storage/storageAccounts/blobServices/generateUserDelegationKey/action"
    ],
    "DataActions": [
    "Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read",
    "Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write"
    ],
    "NotActions": [],
    "AssignableScopes": [
    "/subscriptions/<subscription id>"
    ]

    }
  2. 使用 PowerShell 创建自定义角色

    New-AzureRmRoleDefinition -InputFile“JSON 文件的路径”

此外,如果您使用访问 key ,则可以使用帐户 key 生成 SAS toekn。 SAS toekn可以根据您的需要配置权限。关于如何创建SAS token,请引用以下代码。

SharedKeyCredentials credential = new SharedKeyCredentials(accountName, accountKey);

// This is the name of the container and blob that we're creating a SAS to.
String containerName = "mycontainer"; // Container names require lowercase.
String blobName = "HelloWorld.txt"; // Blob names can be mixed case.
String snapshotId = "2018-01-01T00:00:00.0000000Z"; // SAS can be restricted to a specific snapshot

/*
Set the desired SAS signature values and sign them with the shared key credentials to get the SAS query
parameters.
*/
ServiceSASSignatureValues values = new ServiceSASSignatureValues()
.withProtocol(SASProtocol.HTTPS_ONLY) // Users MUST use HTTPS (not HTTP).
.withExpiryTime(OffsetDateTime.now().plusDays(2)) // 2 days before expiration.
.withContainerName(containerName)
.withBlobName(blobName)
.withSnapshotId(snapshotId);

/*
To produce a container SAS (as opposed to a blob SAS), assign to Permissions using ContainerSASPermissions, and
make sure the blobName and snapshotId fields are null (the default).
*/
BlobSASPermission permission = new BlobSASPermission()
.withRead(true)
.withAdd(true)
.withWrite(true);
values.withPermissions(permission.toString());

SASQueryParameters params = values.generateSASQueryParameters(credential);

更多详情可以引用sample .

关于java - 使用服务主体验证存储帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com