我和我的同事正在开发Spring Boot项目以供学习。我们使用 AWS S3 作为存储图像的云存储。此外,我们决定使用 AWS CloudFront 作为内容分发网络来检索图像,并使用 CloudFront 原始访问身份 (OAI) 来访问 S3 存储桶。为此,我们的服务器使用 ssl 私钥和 keyPairId 生成签名的 url。 代码看起来像这样:
@Value("${cloud.front.distribution.domain}")
String distributionDomain;
@Value("${cloud.front.key.pair.id}")
private String keyPairId;
@Value("${cloud.front.private.key.filePath}")
String privateKeyFilePath;
try {
return CloudFrontUrlSigner.getSignedURLWithCannedPolicy(SignerUtils.Protocol.https,
distributionDomain, new File(privateKeyFilePath), fileName,
keyPairId, calendar.getTime());
} catch (Exception e) {
throw new RuntimeException("Can't generate signed URL", e);
}
当我使用 localhost 时一切正常,但是当项目部署在 AWS Elastic Beanstalk 上时它会出现 500 错误。
我在想问题是带有私钥的文件位于静态目录中,在部署阶段无法读取。但搬迁到其他地方并没有帮助。我很难理解我必须向哪个方向搜索。
我会将您的私钥存储在您在应用程序部署时检索的 S3 存储桶中。
您可以通过创建一个
.ebextension
来做到这一点,例如 00_copy_private_key.config
使用附加到 EC2 实例的实例角色来安全地连接到包含您的私钥的 s3 存储桶。
# Replace `elasticbeanstalk-eu-central-1-xxxxxxxxxxxx` with the bucket that AWS created
# when you created your first Elastic Beanstalk environment.
# Make sure that the IAM Role for the EC2 Instance set in the Elastic Beanstalk configuration
# has attached the `AWSElasticBeanstalkFullAccess` policy.
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Auth:
type: "s3"
buckets: ["elasticbeanstalk-eu-central-1-xxxxxxxxxxxx"]
roleName:
"Fn::GetOptionSetting":
Namespace: "aws:autoscaling:launchconfiguration"
OptionName: "IamInstanceProfile"
DefaultValue: "aws-elasticbeanstalk-ec2-role"
# From the created bucket, point to the .env file which you want to
# copy to this app during deployment.
# The file will be copied first in /tmp/.env, then moved to the app
# in the deployment process.
files:
"/tmp/private.key":
mode: "000400"
owner: root
group: root
authentication: "S3Auth"
source: https://elasticbeanstalk-eu-central-1-xxxxxxxxxxxx.s3.eu-central-1.amazonaws.com/private.key
复制私钥后,您仍然需要将其移动到应用程序期望的正确位置:
container_commands:
00_copy_private_key:
command: "mv /tmp/private.key /var/app/staging/private.key"