투케이2K

487. (javaScript) 자바스크립트 GetBucketPolicy 사용해 AWS S3 특정 버킷에 적용 된 정책 조회 수행 본문

JavaScript

487. (javaScript) 자바스크립트 GetBucketPolicy 사용해 AWS S3 특정 버킷에 적용 된 정책 조회 수행

투케이2K 2026. 2. 5. 20:41
728x90

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

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

- 개발 환경 : Web


- 개발 기술 : JavaScript (자바스크립트) / AWS / S3 / GetBucketPolicy


- 사전) AWS S3 개념 정리 : 

  >> AWS S3 (Amazon Simple Storage Service) 는 AWS 에서 제공하는 객체 스토리지 서비스로, 인터넷을 통해 데이터를 저장하고 검색할 수 있도록 설계되었습니다

  >> 기본 용어 정리 : 

    - 객체(Object): S3에 저장되는 데이터 단위. 파일과 메타데이터로 구성됩니다

    - 버킷(Bucket): 객체를 저장하는 컨테이너. S3에서 데이터를 저장하려면 먼저 버킷을 생성해야 합니다

    - 키(Key): 객체를 식별하는 고유한 이름. 버킷 내에서 객체를 구분하는 데 사용됩니다

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





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

<!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 accessKey = 'AK..7Q'; // [IAM 액세스 키]
        const secretKey = 'Zz..xj'; // [IAM 시크릿 키]

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

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

          try {

            // -----------------------------------------
            // [AWS.config 지정]
            // -----------------------------------------       
            AWS.config.update({
              region: region,
              accessKeyId: accessKey,
              secretAccessKey: secretKey
            });


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


            // -----------------------------------------
            // [요청 파라미터 생성]
            // -----------------------------------------
            const param = { // ✅ 버킷 명칭 지정
              Bucket: 'service'
            };


            // -----------------------------------------
            // [GetBucketPolicy] : S3 버킷에 설정된 버킷 정책 조회 수행
            // -----------------------------------------
            // AWS 참고 사이트 : https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicy.html
            // -----------------------------------------
            aws.getBucketPolicy( param , function(err, data) {             
              if (err) {
                console.error("");
                console.error("=========================================");
                console.error("[getBucketPolicy] : [Error]");
                console.error("---------------------------------------");
                console.error(err);
                console.error("=========================================");
                console.error("");

                // ---------------------------------------------
                // ✅ [주요 에러 정리]
                // ---------------------------------------------
                // AccessDenied : 호출자가 s3:GetBucketPolicy 권한 없음
                // ---------------------------------------------
                // MethodNotAllowed : 호출자가 버킷 소유 계정이 아닌 경우
                // ---------------------------------------------
                // NoSuchBucketPolicy : 버킷에 정책이 전혀 없는 경우
                // ---------------------------------------------
                // InvalidAccessPointAliasError : Access Point 또는 Object Lambda Access Point alias가 잘못된 경우
                // ---------------------------------------------


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


                // ---------------------------------------------
                // [에러 출력]
                // ---------------------------------------------
                document.write(JSON.stringify(errJson));
                // ---------------------------------------------

              } else {
                console.log("");
                console.log("=========================================");
                console.log("[getBucketPolicy] : [Result]");
                console.log("---------------------------------------");
                console.log(data);
                console.log("=========================================");
                console.log("");

                // ---------------------------------------------
                // ✅ [로그 출력 예시 첨부]
                // ---------------------------------------------
                // response 데이터에서 Policy 데이터 파싱 수행
                // ---------------------------------------------
                /*
                {
                  "Version": "2012-10-17",
                  "Id": "Policy123456789012",
                  "Statement": [
                    {
                      "Sid": "Stmt123456789012",
                      "Effect": "Allow",
                      "Principal": "*",
                      "Action": "s3:GetObject",
                      "Resource": "arn:aws:s3:::service/*"
                    },
                    {
                      "Sid": "RestrictToTLSRequestsOnly",
                      "Effect": "Deny",
                      "Principal": "*",
                      "Action": "s3:*",
                      "Resource": [
                        "arn:aws:s3:::service",
                        "arn:aws:s3:::service/*"
                      ],
                      "Condition": {
                        "Bool": {
                          "aws:SecureTransport": "false"
                        }
                      }
                    }
                  ]
                }
                */
                // ---------------------------------------------


                // ---------------------------------------------
                // [Body 표시 JSON]
                // ---------------------------------------------
                var jsonParse = null;
                try {
                  if (data.hasOwnProperty('Policy') == true){
                    jsonParse = JSON.parse(data.Policy);
                  }
                  else {
                    jsonParse = data;  
                  }                  
                }
                catch(err){
                  console.error("Json Parsing Error : ", err);
                  jsonParse = data;
                }

                var resJson = {
                  response: "result",
                  data: jsonParse
                }
                // ---------------------------------------------


                // ---------------------------------------------
                // [결과 출력]
                // ---------------------------------------------
                document.write(JSON.stringify(resJson));
                // ---------------------------------------------

              }

            });

          }
          catch (exception) {
            console.error("");
            console.error("=========================================");
            console.error("[window onload] : [Exception] : 예외 상황 발생");
            console.error("-----------------------------------------");
            console.error(exception);
            console.error("=========================================");
            console.error("");

            // ---------------------------------------------
            // [Body 표시 JSON]
            // ---------------------------------------------
            var errJson = {
              response: "exception",
              data: exception.message
            }
            // ---------------------------------------------


            // ---------------------------------------------
            // [에러 출력]
            // ---------------------------------------------
            document.write(JSON.stringify(errJson));
            // ---------------------------------------------

          }

        };

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

    </script>


</head>


<body>

</body>

</html>

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





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

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

https://kkh0977.tistory.com/7619

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