본문 바로가기
lambda-python3.8

람다 Python Signed Url 만들기 S3 + Cloud Front

by 2세1의 행복한 개발 2021. 3. 3.
반응형

boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#examples

 

CloudFront — Boto3 Docs 1.17.18 documentation

Id (string) -- [REQUIRED] The unique identifier for the cache policy. If the cache policy is attached to a distribution’s cache behavior, you can get the policy’s identifier using ListDistributions or GetDistribution . If the cache policy is not attach

boto3.amazonaws.com

에서 제공하는 샘플을 보고 api를 작성했으나 실패하였다

import datetime

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from botocore.signers import CloudFrontSigner


def rsa_signer(message):
    with open('path/to/key.pem', 'rb') as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())

key_id = 'AKIAIOSFODNN7EXAMPLE'
url = 'http://d2949o5mkkp72v.cloudfront.net/hello.txt'
expire_date = datetime.datetime(2017, 1, 1)

cloudfront_signer = CloudFrontSigner(key_id, rsa_signer)

# Create a signed url that will be valid until the specfic expiry date
# provided using a canned policy.
signed_url = cloudfront_signer.generate_presigned_url(
    url, date_less_than=expire_date)
print(signed_url)

cryptography쪽에서 에러가 나기 시작했는데 찾기가 쉽지 않다

그래서 다음 코드를 추가했습니다

 

해당 api를 클래스로 만들었다

import boto3
from botocore.signers import CloudFrontSigner
import time
import rsa
from datetime import datetime

class AwsConfig:

    ServiceCfUrl = "https://.cloudfront.net"
    ACCESS_KEY = "AK"
    SECRET_KEY = "vm"
    S3_BUCKET_CMS_SERVICE = "cms-service"
    CF_PEM_KEY = "Key.pem"

    def makeSignedUrl(key):

        # s3 client 생성
        s3_client = boto3.client('s3')
        key_pair_id = "AQ"
        priv_key_file = AwsConfig.CF_PEM_KEY
        resource = AwsConfig.ServiceCfUrl + "/" +key

        expires = int(time.time()) + 300  # 5분

        # 1.pem 키 tmp 폴더에 다운
        s3_client.download_file(AwsConfig.S3_BUCKET_CMS_SERVICE, priv_key_file, "/tmp/" + priv_key_file)

        # priv_key_string = open("/tmp/"+priv_key_file,'r').read()
        cf_signer = CloudFrontSigner(key_pair_id, AwsConfig.rsa_signer)
        # url 생성
        signed_url = cf_signer.generate_presigned_url(resource, date_less_than=datetime.fromtimestamp(expires))

        return signed_url

    def rsa_signer(message):
        private_key = open("/tmp/pey.pem", 'r').read()
        return rsa.sign(
            message,
            rsa.PrivateKey.load_pkcs1(private_key.encode('utf8')),
            'SHA-1')  # CloudFront requires SHA-1 hash

가장 핵심은

람다에서 pem키를 불러오는 부분인데 해당 폴더 위치를 모르기 때문에

s3에 접근하여 pem를 다운받아 저장한다

import를 하여 AwsConfig.makeSignedUrl를 호출하여 s3경로를 입력해주면 끝이다.

 

 

댓글