투케이2K

411. (javaScript) 자바스크립트 AWS STS 임시 자격 증명 사용해 S3 Get PreSignedUrl 프리 사인 URL 주소 생성 본문

JavaScript

411. (javaScript) 자바스크립트 AWS STS 임시 자격 증명 사용해 S3 Get PreSignedUrl 프리 사인 URL 주소 생성

투케이2K 2025. 7. 18. 20:05
728x90

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web

- 개발 기술 : JavaScript (자바스크립트) / AWS / STS / S3 / PreSignedUrl / Get Api

- 사전) AWS S3 간략 설명 : 

  >> Aws S3 버킷 이란 데이터 (사진, 동영상, 문서 등) 객체 를 업로드할 수 있는 컨테이너 (디렉토리) 입니다

  >> Aws S3 버킷은 온라인 스토리지 서비스로 HTTP/HTTPS 를 통한 API 를 사용해 파일 업로드 및 다운로드 처리를 할 수 있습니다

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko">
<head>
    <title>javaScriptTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">


    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">


    <!-- 내부 CSS 스타일 지정 -->
    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin : 0 auto;
            padding : 0;
            border : none;
            background-color: #666;
        }

    </style>





    <!-- [CDN 주소 설정] -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1416.0.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script>

        // --------------------------------------------------------------------------------------------------------------

        // [전역 변수 선언]
        const region = 'ap-northeast-2'; // [AWS 리전]
        const accessKeyId = 'AK..7Q'; // [IAM 액세스 키]
        const secretAccessKey = 'Zz..xj'; // [IAM 시크릿 키]
        
        const bucket = 'service-folder'; // [S3 버킷 이름]
        const key = 'apps/test.apk'; // [S3 폴더 및 파일 경로]
        const expiredTime = 36000; // [STS 임시 자격 증명 및 파일 다운 로드 유효 시간]

        // --------------------------------------------------------------------------------------------------------------

        // [html 최초 로드 및 이벤트 상시 대기 실시]
        window.onload = function() {
            console.log("");
            console.log("=========================================");
            console.log("[window onload] : [start]");
            console.log("=========================================");
            console.log("");


            // -----------------------------------------
            // [AWS.config 지정] : 1차 IAM 계정
            // -----------------------------------------
            AWS.config.update({
              region: region,
              accessKeyId: accessKeyId,
              secretAccessKey: secretAccessKey
            });



            // -----------------------------------------
            // [AWS.STS 객체 생성]
            // -----------------------------------------
            const sts = new AWS.STS();


            // -----------------------------------------
            // [STS getSessionToken 호출 수행]
            // -----------------------------------------
            // DurationSeconds : Expiration 시간 3600 은 (1시간) / 세션 지속 시간 (최대 129600초 = 36시간)
            // -----------------------------------------          
            sts.getSessionToken({ DurationSeconds: expiredTime }, function(err, data) {
              if (err) {
                console.error("");
                console.error("=========================================");
                console.error("[getSessionToken] : [Error]");
                console.error("---------------------------------------");
                console.error(err);					
                console.error("=========================================");
                console.error("");

                // [Body 표시 JSON]
                var errJson = {
                  respones: "error",
                  data: err
                }

                //document.body.innerHTML = JSON.stringify(errJson); // [1 표시]
                document.body.write(JSON.stringify(errJson)); // [2 표시]     

              } else {
                console.log("");
                console.log("=========================================");
                console.log("[getSessionToken] : [Success]");

                console.log("---------------------------------------");
                console.log("AccessKeyId :: " + data.Credentials.AccessKeyId); // [STS > AccessKeyId]
                console.log("SecretAccessKey :: " + data.Credentials.SecretAccessKey); // [STS > SecretAccessKey]
                console.log("SessionToken :: " + data.Credentials.SessionToken); // [STS > SessionToken]
                console.log("Expiration :: " + data.Credentials.Expiration); // [STS > Expiration]
                console.log("=========================================");
                console.log("");


                // [void 클로저 함수 정의 실시]
                let voidFunction = async function(){
                    console.log("");
                    console.log("=========================================");
                    console.log("[voidFunction] : [start]");
                    console.log("=========================================");
                    console.log("");

                    // -----------------------------------------
                    // [AWS.config 지정] : 2차 내려 받은 STS 임시 접근 계정
                    // -----------------------------------------
                    AWS.config.update({
                      region: region,
                      accessKeyId: data.Credentials.AccessKeyId,
                      secretAccessKey: data.Credentials.SecretAccessKey,
                      sessionToken: data.Credentials.SessionToken,
                      signatureVersion: "v4", // [API 요청용 AWS Signature Version 4]
                    });


                    // -----------------------------------------
                    // [AWS.S3 객체 생성]
                    // -----------------------------------------
                    const s3 = new AWS.S3();


                    // -----------------------------------------
                    // [GET 확인 용도 : Pre-Signed URL 생성 요청]
                    // -----------------------------------------
                    const getExpiresInSeconds = expiredTime; // 파일 다운로드 만료 시간
                    const getParams = {
                      Bucket: bucket, // [버킷 이름]
                      Key: key, // [폴더 및 파일 경로]
                      Expires: getExpiresInSeconds // [URL 유효 시간 (초)]
                    }; 

                    const getUrl = await s3.getSignedUrl('getObject', getParams);

                    console.log("");
                    console.log("=========================================");
                    console.log("[Get - PreSignedUrl] : [Success]");
                    console.log("---------------------------------------");
                    console.log("url :: " + getUrl); 
                    console.log("=========================================");
                    console.log("");


                    // -----------------------------------------
                    // [Body 표시 JSON]
                    // -----------------------------------------
                    var resJson = {
                      respones: "success",
                      data: {
                        getPreSignedUrl: getUrl
                      }
                    }


                    //document.body.innerHTML = JSON.stringify(resJson); // [1 표시]
                    document.write(JSON.stringify(resJson)); // [2  표시]
                };


                voidFunction(); // [클로저 함수 호출]

              }
            });

        };

        // --------------------------------------------------------------------------------------------------------------

    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

[Aws S3 Storage] PreSignedUrl 프리 사인 URL 주소 정리 - S3 버킷 저장소 Get 확인 및 Put 업로드 임시 권한 주소

https://blog.naver.com/kkh0977/223903771897


[Aws S3 Storage] S3 (Amazon Simple Storage Service) 버킷 저장소 개념 및 설명 정리

https://blog.naver.com/kkh0977/223733087281?trackingCode=blog_bloghome_searchlist


[[간단 소스] Aws S3 버킷 저장소 리스트 목록 확인 - AmazonS3 listBuckets]

https://blog.naver.com/kkh0977/223797258160?trackingCode=blog_bloghome_searchlist


[자바스크립트 AWS S3 Get 요청 및 Put 업로드 PreSignedUrl 프리 사인 URL 주소 생성 수행 - getSignedUrl]

https://blog.naver.com/kkh0977/223903767776

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments