選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

CreateGrant 搭配 AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateGrant 搭配 AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 CreateGrant

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); // The identity that is given permission to perform the operations // specified in the grant. var grantee = "arn:aws:iam::111122223333:role/ExampleRole"; // The identifier of the AWS KMS key to which the grant applies. You // can use the key ID or the Amazon Resource Name (ARN) of the KMS key. var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4"; var request = new CreateGrantRequest { GranteePrincipal = grantee, KeyId = keyId, // A list of operations that the grant allows. Operations = new List<string> { "Encrypt", "Decrypt", }, }; var response = await client.CreateGrantAsync(request); string grantId = response.GrantId; // The unique identifier of the grant. string grantToken = response.GrantToken; // The grant token. Console.WriteLine($"Id: {grantId}, Token: {grantToken}"); } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考中的 CreateGrant

CLI
AWS CLI

建立授予

下列create-grant範例會建立授予,允許使用者exampleUser1234abcd-12ab-34cd-56ef-1234567890ab範例 KMS 金鑰上使用 decrypt命令。淘汰主體是 adminRole角色。只有在decrypt請求中的加密內容包含"Department": "IT"金鑰/值對時,授予才會使用EncryptionContextSubset授予限制來允許此許可。

aws kms create-grant \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --grantee-principal arn:aws:iam::123456789012:user/exampleUser \ --operations Decrypt \ --constraints EncryptionContextSubset={Department=IT} \ --retiring-principal arn:aws:iam::123456789012:role/adminRole

輸出:

{ "GrantId": "1a2b3c4d2f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2", "GrantToken": "<grant token here>" }

若要檢視授予的詳細資訊,請使用 list-grants命令。

如需詳細資訊,請參閱 AWS 金鑰管理服務開發人員指南中的 AWS KMS 中的授與

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 CreateGrant

Java
SDK for Java 2.x
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Grants permissions to a specified principal on a customer master key (CMK) asynchronously. * * @param keyId The unique identifier for the customer master key (CMK) that the grant applies to. * @param granteePrincipal The principal that is given permission to perform the operations that the grant permits on the CMK. * @return A {@link CompletableFuture} that, when completed, contains the ID of the created grant. * @throws RuntimeException If an error occurs during the grant creation process. */ public CompletableFuture<String> grantKeyAsync(String keyId, String granteePrincipal) { List<GrantOperation> grantPermissions = List.of( GrantOperation.ENCRYPT, GrantOperation.DECRYPT, GrantOperation.DESCRIBE_KEY ); CreateGrantRequest grantRequest = CreateGrantRequest.builder() .keyId(keyId) .name("grant1") .granteePrincipal(granteePrincipal) .operations(grantPermissions) .build(); CompletableFuture<CreateGrantResponse> responseFuture = getAsyncClient().createGrant(grantRequest); responseFuture.whenComplete((response, ex) -> { if (ex == null) { logger.info("Grant created successfully with ID: " + response.grantId()); } else { if (ex instanceof KmsException kmsEx) { throw new RuntimeException("Failed to create grant: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred: " + ex.getMessage(), ex); } } }); return responseFuture.thenApply(CreateGrantResponse::grantId); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考中的 CreateGrant

Kotlin
SDK for Kotlin
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createNewGrant( keyIdVal: String?, granteePrincipalVal: String?, operation: String, ): String? { val operationOb = GrantOperation.fromValue(operation) val grantOperationList = ArrayList<GrantOperation>() grantOperationList.add(operationOb) val request = CreateGrantRequest { keyId = keyIdVal granteePrincipal = granteePrincipalVal operations = grantOperationList } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.createGrant(request) return response.grantId } }
  • 如需 API 詳細資訊,請參閱 SDK AWS for Kotlin API 參考中的 CreateGrant

PHP
SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/*** * @param string $keyId * @param string $granteePrincipal * @param array $operations * @param array $grantTokens * @return Result */ public function createGrant(string $keyId, string $granteePrincipal, array $operations, array $grantTokens = []) { $args = [ 'KeyId' => $keyId, 'GranteePrincipal' => $granteePrincipal, 'Operations' => $operations, ]; if($grantTokens){ $args['GrantTokens'] = $grantTokens; } try{ return $this->client->createGrant($args); }catch(KmsException $caught){ if($caught->getAwsErrorMessage() == "InvalidGrantTokenException"){ echo "The request was rejected because the specified grant token is not valid.\n"; } throw $caught; } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考中的 CreateGrant

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class GrantManager: def __init__(self, kms_client): self.kms_client = kms_client @classmethod def from_client(cls) -> "GrantManager": """ Creates a GrantManager instance with a default KMS client. :return: An instance of GrantManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def create_grant( self, key_id: str, principal: str, operations: [str] ) -> dict[str, str]: """ Creates a grant for a key that lets a principal generate a symmetric data encryption key. :param key_id: The ARN or ID of the key. :param principal: The principal to grant permission to. :param operations: The operations to grant permission for. :return: The grant that is created. """ try: return self.kms_client.create_grant( KeyId=key_id, GranteePrincipal=principal, Operations=operations, ) except ClientError as err: logger.error( "Couldn't create a grant on key %s. Here's why: %s", key_id, err.response["Error"]["Message"], ) raise
  • 如需 API 詳細資訊,請參閱 SDK AWS for Python (Boto3) API 參考中的 CreateGrant

AWS SDK for .NET
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

public static async Task Main() { var client = new AmazonKeyManagementServiceClient(); // The identity that is given permission to perform the operations // specified in the grant. var grantee = "arn:aws:iam::111122223333:role/ExampleRole"; // The identifier of the AWS KMS key to which the grant applies. You // can use the key ID or the Amazon Resource Name (ARN) of the KMS key. var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4"; var request = new CreateGrantRequest { GranteePrincipal = grantee, KeyId = keyId, // A list of operations that the grant allows. Operations = new List<string> { "Encrypt", "Decrypt", }, }; var response = await client.CreateGrantAsync(request); string grantId = response.GrantId; // The unique identifier of the grant. string grantToken = response.GrantToken; // The grant token. Console.WriteLine($"Id: {grantId}, Token: {grantToken}"); } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考中的 CreateGrant

下一個主題:

CreateKey

上一個主題:

CreateAlias
隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。