

# 使用预签名 URL 共享对象
<a name="S3OutpostsShareObjectPresignedURL"></a>

要授予对 Outpost 本地存储对象的限时访问权限而不更新存储桶策略，您可以使用预签名 URL。借助预签名 URL，作为存储桶的所有者，您可以与您虚拟私有云（VPC）中的个人共享对象，或者向其授予上传或删除对象的权限。

使用 AWS SDK 或 AWS Command Line Interface（AWS CLI）创建预签名 URL 时，您会将该 URL 与某个特定的操作关联。您还可以通过选择自定义到期时间来授予对预签名 URL 的限时访问权限，自定义到期时间最短可为 1 秒，最长可为 7 天。共享预签名 URL 时，VPC 中的个人可以执行嵌入在 URL 中的操作，如同他们就是原始签名用户。URL 在到达其到期时间时将会过期，不再有效。



创建预签名 URL 时，必须提供您的安全凭证，然后指定以下内容：
+ 该 Amazon S3 on Outposts 存储桶的一个访问点 Amazon 资源名称（ARN）
+ 一个对象键
+ 一个 HTTP方法（`GET` 用于下载对象）
+ 一个到期日期和时间

预签名 URL 仅在指定的有效期内有效。也就是说，您必须在到期日期和时间到达之前启动该 URL 允许的操作。在到期日期和时间到达之前，您可以多次使用预签名 URL。如果您已使用临时令牌创建了预签名 URL，则此 URL 将在令牌过期时过期，即使您使用更晚的到期时间创建了该 URL。

虚拟私有云（VPC）中有权访问预签名 URL 的用户可以访问对象。例如，如果您在桶中具有一段视频，并且桶和对象均为私有，您可以通过生成预签名的 URL 来与其他用户共享视频。由于预签名 URL 将向持有该 URL 的任何人授予访问 S3 on Outposts 存储桶的权限，我们建议您妥善保护这些 URL。有关保护预签名 URL 的更多详细信息，请参阅 [限制预签名 URL 功能](S3OutpostsPresignedURL.md#S3OutpostsPresignedUrlUploadObjectLimitCapabilities)。

具有有效安全凭证的任何人都可以创建预签名 URL。但必须由拥有执行预签名 URL 所基于的操作权限的人创建该预签名 URL。有关更多信息，请参阅 [谁可以创建预签名 URL](S3OutpostsPresignedURL.md#S3Outpostswho-presigned-url)。

您可以使用 AWS SDK 和 AWS CLI 生成预签名 URL 以共享 S3 on Outposts 存储桶中的对象。有关更多信息，请参阅以下示例。

## 使用 AWS SDK
<a name="S3OutpostsShareObjectPreSignedURLSDK"></a>

您可以使用 AWS SDK 生成可以提供给其他人的预签名 URL，以便他们可以检索对象。

**注意**  
使用 AWS SDK 生成预签名 URL 时，预签名 URL 的最长到期时间为创建之时起 7 天。

------
#### [ Java ]

**Example**  
以下示例将生成一个预签名 URL，您可以将其提供给其他人，以便他们可以检索 S3 on Outposts 存储桶的对象。有关更多信息，请参阅 [使用适用于 S3 on Outposts 的预签名 URL](S3OutpostsPresignedURL.md)。要使用此示例，请将 *`user input placeholders`* 替换为您自己的信息。  

```
import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;

import java.io.IOException;
import java.net.URL;
import java.time.Instant;

public class GeneratePresignedURL {

    public static void main(String[] args) throws IOException {
        Regions clientRegion = Regions.DEFAULT_REGION;
        String accessPointArn = "*** access point ARN ***";
        String objectKey = "*** object key ***";

        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // Set the presigned URL to expire after one hour.
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = Instant.now().toEpochMilli();
            expTimeMillis += 1000 * 60 * 60;
            expiration.setTime(expTimeMillis);

            // Generate the presigned URL.
            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(accessPointArn, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);
            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

            System.out.println("Pre-Signed URL: " + url.toString());
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process 
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}
```

------
#### [ .NET ]

**Example**  
以下示例将生成一个预签名 URL，您可以将其提供给其他人，以便他们可以检索 S3 on Outposts 存储桶的对象。有关更多信息，请参阅 [使用适用于 S3 on Outposts 的预签名 URL](S3OutpostsPresignedURL.md)。要使用此示例，请将 *`user input placeholders`* 替换为您自己的信息。  

```
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;

namespace Amazon.DocSamples.S3
{
    class GenPresignedURLTest
    {
        private const string accessPointArn = "*** access point ARN ***"; 
        private const string objectKey = "*** object key ***";
        // Specify how long the presigned URL lasts, in hours.
        private const double timeoutDuration = 12;
        // Specify your bucket Region (an example Region is shown).
        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
        private static IAmazonS3 s3Client;

        public static void Main()
        {
            s3Client = new AmazonS3Client(bucketRegion);
            string urlString = GeneratePreSignedURL(timeoutDuration);
        }
        static string GeneratePreSignedURL(double duration)
        {
            string urlString = "";
            try
            {
                GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
                {
                    BucketName = accessPointArn,
                    Key = objectKey,
                    Expires = DateTime.UtcNow.AddHours(duration)
                };
                urlString = s3Client.GetPreSignedURL(request1);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            return urlString;
        }
    }
}
```

------
#### [ Python ]

使用适用于 Python (Boto3) 的 SDK 生成预签名 URL 以共享对象。例如，使用 Boto3 客户端和 `generate_presigned_url` 函数生成一个允许您 `GET` 对象的预签名 URL。

```
import boto3
    url = boto3.client('s3').generate_presigned_url(
    ClientMethod='get_object', 
    Params={'Bucket': 'ACCESS_POINT_ARN', 'Key': 'OBJECT_KEY'},
    ExpiresIn=3600)
```

有关使用适用于 Python 的 SDK（Boto3）生成预签名 URL 的更多信息，请参阅《AWS SDK for Python (Boto) API 参考》**中的 [Python](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.generate_presigned_url)。

------

## 使用 AWS CLI
<a name="S3OutpostsShareObjectPresignedCLI"></a>

以下示例 AWS CLI 命令将为一个 S3 on Outposts 存储桶生成一个预签名 URL。要使用此示例，请将 *`user input placeholders`* 替换为您自己的信息。

**注意**  
使用 AWS CLI 生成预签名 URL 时，预签名 URL 的最长到期时间为创建之时起 7 天。

```
aws s3 presign s3://arn:aws:s3-outposts:us-east-1:111122223333:outpost/op-01ac5d28a6a232904/accesspoint/example-outpost-access-point/mydoc.txt --expires-in 604800
```

有关更多信息，请参阅《AWS CLI 命令参考》中的 [presign](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/presign.html)。