

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 AWS 软件开发工具包在 Rust 中实现亚马逊验证权限
<a name="code-samples-rust"></a>

本主题提供了使用 AWS 软件开发工具包在 Rust 中实现 Amazon 验证权限的实际示例。此示例说明如何开发一种可以测试用户是否能够查看照片的授权模型。示例代码使用来自 [aws-sdk-verifiedpermissions](https://docs.rs/aws-sdk-verifiedpermissions/latest/aws_sdk_verifiedpermissions/)crate [适用于 Rust 的 AWS SDK](https://github.com/awslabs/aws-sdk-rust)，它提供了一组用于与 AWS 服务之交互的强大工具。

## 先决条件
<a name="rust-prereqs"></a>

 在开始之前，请确保在系统上配置了 [AWS CLI](https://aws.amazon.com/cli/)，并且熟悉 Rust。
+ 有关安装的说明 AWS CLI，请参阅 [AWS CLI 安装指南](https://docs.aws.amazon.com//cli/latest/userguide/getting-started-install.html)。
+ 有关配置的说明 AWS CLI，请参阅[中的[配置设置 AWS CLI](https://docs.aws.amazon.com//cli/latest/userguide/cli-configure-quickstart.html)和配置和凭据文件设置](https://docs.aws.amazon.com//cli/latest/userguide/cli-configure-profiles.html)。 AWS CLI
+ 有关 Rust 的更多信息，请参阅 [rust-lang.org](https://www.rust-lang.org/) 和 Rust [AWS 开发工具包开发人员指南](https://docs.aws.amazon.com//sdk-for-rust/latest/dg/welcome.html)。

准备好环境后，让我们来探讨如何在 Rust 中实现已验证的权限。

## 测试示例代码
<a name="rust-code"></a>

示例代码执行以下操作：
+ 设置要与之通信的 SDK 客户端 AWS
+ 创建[策略存储](policy-stores.md)
+ [通过添加架构来定义策略存储的结构](schema.md)
+ 添加用于检查授权请求的[策略](policies.md)
+ 发送测试[授权请求](authorization.md)以验证所有设置是否正确

**测试示例代码**

1. 创建一个 Rust 项目。

1. 将中的`main.rs`任何现有代码替换为以下代码：

   ```
   use std::time::Duration;
   use std::thread::sleep;
   use aws_config::BehaviorVersion;
   use aws_sdk_verifiedpermissions::Client;
   use aws_sdk_verifiedpermissions::{
       operation::{
           create_policy::CreatePolicyOutput,
           create_policy_store::CreatePolicyStoreOutput,
           is_authorized::IsAuthorizedOutput,
           put_schema::PutSchemaOutput,
       },
       types::{
           ActionIdentifier, EntityIdentifier, PolicyDefinition, SchemaDefinition, StaticPolicyDefinition, ValidationSettings
       },
   };
   
   //Function that creates a policy store in the client that's passed
   async fn create_policy_store(client: &Client, valid_settings: &ValidationSettings)-> CreatePolicyStoreOutput {
       let policy_store = client.create_policy_store().validation_settings(valid_settings.clone()).send().await;
       return policy_store.unwrap();
   }
   
   //Function that adds a schema to the policy store in the client
   async fn put_schema(client: &Client, ps_id: &str, schema: &str) -> PutSchemaOutput {
       let schema = client.put_schema().definition(SchemaDefinition::CedarJson(schema.to_string())).policy_store_id(ps_id.to_string()).send().await;
       return schema.unwrap();
   }
   
   //Function that creates a policy in the policy store in the client
   async fn create_policy(client: &Client, ps_id: &str, policy_definition:&PolicyDefinition) -> CreatePolicyOutput {
       let create_policy = client.create_policy().definition(policy_definition.clone()).policy_store_id(ps_id).send().await;
       return create_policy.unwrap();
   }
   
   //Function that tests the authorization request to the policy store in the client
   async fn authorize(client: &Client, ps_id: &str, principal: &EntityIdentifier, action: &ActionIdentifier, resource: &EntityIdentifier) -> IsAuthorizedOutput {
       let is_auth = client.is_authorized().principal(principal.to_owned()).action(action.to_owned()).resource(resource.to_owned()).policy_store_id(ps_id).send().await;
       return is_auth.unwrap();
   }
   
   #[::tokio::main]
   async fn main() -> Result<(), aws_sdk_verifiedpermissions::Error> {
   
   //Set up SDK client
       let config = aws_config::load_defaults(BehaviorVersion::latest()).await;
       let client = aws_sdk_verifiedpermissions::Client::new(&config);
   
   //Create a policy store
       let valid_settings = ValidationSettings::builder()
       .mode({aws_sdk_verifiedpermissions::types::ValidationMode::Strict
       })
       .build()
       .unwrap();
       let policy_store = create_policy_store(&client, &valid_settings).await;
       println!(
       "Created Policy store with ID: {:?}",
       policy_store.policy_store_id
       );
   
   //Add schema to policy store
       let schema= r#"{
           "PhotoFlash": {
               "actions": {
                   "ViewPhoto": {
                       "appliesTo": {
                           "context": {
                               "type": "Record",
                               "attributes": {}
                           },
                           "principalTypes": [
                               "User"
                           ],
                           "resourceTypes": [
                               "Photo"
                           ]
                       },
                       "memberOf": []
                   }
               },
               "entityTypes": {
                   "Photo": {
                       "memberOfTypes": [],
                       "shape": {
                           "type": "Record",
                           "attributes": {
                               "IsPrivate": {
                                   "type": "Boolean"
                               }
                           }
                       }
                   },
                   "User": {
                       "memberOfTypes": [],
                       "shape": {
                           "attributes": {},
                           "type": "Record"
                       }
                   }
               }
           }
       }"#;
       let put_schema = put_schema(&client, &policy_store.policy_store_id, schema).await;
       println!(
           "Created Schema with Namespace: {:?}",
           put_schema.namespaces
       ); 
   
   //Create policy
       let policy_text = r#"
           permit (
               principal in PhotoFlash::User::"alice",
               action == PhotoFlash::Action::"ViewPhoto",
               resource == PhotoFlash::Photo::"VacationPhoto94.jpg"
           );
           "#;
       let policy_definition = PolicyDefinition::Static(StaticPolicyDefinition::builder().statement(policy_text).build().unwrap()); 
       let policy = create_policy(&client, &policy_store.policy_store_id, &policy_definition).await;
       println!(
           "Created Policy with ID: {:?}",
           policy.policy_id
       ); 
   
   //Break to make sure the resources are created before testing authorization
       sleep(Duration::new(2, 0));
   
   //Test authorization
       let principal= EntityIdentifier::builder().entity_id("alice").entity_type("PhotoFlash::User").build().unwrap();
       let action = ActionIdentifier::builder().action_type("PhotoFlash::Action").action_id("ViewPhoto").build().unwrap();
       let resource = EntityIdentifier::builder().entity_id("VacationPhoto94.jpg").entity_type("PhotoFlash::Photo").build().unwrap();
       let auth = authorize(&client, &policy_store.policy_store_id, &principal, &action, &resource).await;
       println!(
           "Decision: {:?}",
           auth.decision
           );
           println!(
           "Policy ID: {:?}",
           auth.determining_policies
           );
        Ok(())   
   }
   ```

1. 通过在终端`cargo run`中输入来运行代码。

如果代码运行正确，则终端将显示决定策略的策略 ID，`Decision: Allow`后面是确定策略的策略 ID。这意味着您已成功创建策略存储并使用适用于 Rust 的 AWS SDK 对其进行了测试。

## 清理 资源
<a name="rust-clean-up"></a>

浏览完保单存储后，将其删除。

**删除策略存储**  
您可以使用`delete-policy-store`操作删除策略存储，`PSEXAMPLEabcdefg111111`替换为要删除的策略存储 ID。

```
$ aws verifiedpermissions delete-policy-store \
    --policy-store-id PSEXAMPLEabcdefg111111
```

如果成功，此命令不会产生任何输出。