투케이2K

484. (javaScript) 자바스크립트 AWS GetCallerIdentity 사용해 IAM 계정 자격 증명 정보 유효성 검증 본문

JavaScript

484. (javaScript) 자바스크립트 AWS GetCallerIdentity 사용해 IAM 계정 자격 증명 정보 유효성 검증

투케이2K 2026. 2. 1. 15:00
728x90

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

 

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

- 개발 환경 : Web


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


- 사전) GetCallerIdentity API 설명 정리 : 

  >> AWS GetCallerIdentity 는 AWS Security Token Service (STS) 에서 제공하는 API 중 하나로, 호출하는 엔티티 (사용자, 역할, 서비스 등) 의 AWS 계정 정보와 인증된 사용자 정보를 반환하는 기능을 합니다

  >> AWS GetCallerIdentity API 는 STS 임시 정보 인증 및 권한 확인을 위해 자주 사용됩니다

  >> AWS GetCallerIdentity 사용 목적 : 

    - 디버깅 및 인증 확인 : 현재 실행 중인 코드나 애플리케이션이 어떤 IAM 사용자나 역할로 동작하는지 확인할 때 사용

    - Cross-Account Access 검증 : AssumeRole 등을 통해 다른 계정의 리소스에 접근할 때, 실제로 어떤 역할로 인증되었는지 확인

    - 보안 감사 : API 호출이 올바른 IAM 정책과 권한으로 수행되는지 검증

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





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

<!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>

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

        // [전역 변수 선언]
        var accessKey = 'AS..6O'; 
        var secretKey = 'ep..47'; 

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

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

          try {

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


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


            // -----------------------------------------
            // [GetCallerIdentity] : AWS 계정 정보와 인증된 사용자 정보 확인
            // -----------------------------------------
            // AWS 참고 사이트 : https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html
            // -----------------------------------------
            // 입력 파라미터 없음: 단순히 현재 인증된 엔티티의 정보를 반환.
            // -----------------------------------------
            // 권한 요구사항: sts:GetCallerIdentity 권한이 필요.
            // -----------------------------------------
            // 리전 무관: 모든 리전에서 동일하게 동작.
            // -----------------------------------------
            aws.getCallerIdentity( {} , function(err, data) { 
              if (err) {
                console.error("=========================================");
                console.error("[getCallerIdentity] : [Error] : ", err);
                console.error("---------------------------------------");
                console.error(err.code);
                console.error("---------------------------------------");
                console.error(err.message);							
                console.error("=========================================");


                // ---------------------------------------------
                // ✅ [주요 에러 정리]
                // ---------------------------------------------
                // AccessDenied : 정책 혹은 권한 문제로 호출 실패. HTTP 403.
                // InvalidClientTokenId : 제공된 토큰이 AWS 기록에 없거나 잘못된 경우. 
                // ExpiredToken : 세션 토큰이 만료된 경우. 예: "The security token included in the request is expired".
                // IncompleteSignature : 요청 시그니처가 불완전하거나 서명 오류. HTTP 403.
                // MissingAuthenticationToken : 인증 토큰이 누락된 경우. HTTP 403.
                // RequestExpired : 요청 시간이 유효시간 초과된 경우. HTTP 400.
                // InternalFailureAWS : 내부 오류로 인해 처리 실패. HTTP 500.
                // ServiceUnavailable : 서비스 일시 중단 상태. HTTP 503.
                // ---------------------------------------------

              } else {

                console.log("[getCallerIdentity] : [Success] : ", JSON.stringify(data));

                // ---------------------------------------------
                // ✅ [로그 출력 예시 첨부]
                // ---------------------------------------------
                /*
                {
                  "ResponseMetadata": {
                    "RequestId": "d3c30b16-6516-46ac-bfce-634439e4f4f0"
                  },
                  "UserId": "AI..2S", // 호출자의 고유 사용자 ID
                  "Account": "123456789012", // 호출자의 AWS 계정 ID
                  "Arn": "arn:aws:iam::123456789012:user/2k@twok.com-CLI" // 호출자의 Amazon Resource Name (ARN)
                }
                */
                // ---------------------------------------------

              }

            });

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

          }

        };

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

    </script>


</head>


<body>

</body>

</html>

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





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

[Aws Security Token Service] Aws STS 임시 보안 자격 증명 설명 정리

https://kkh0977.tistory.com/7942

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


[AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 AWS STS 임시 정보 호출 람다 생성

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


[자바스크립트 AWS STS 임시 자격 증명 사용해 S3 Get PreSignedUrl 프리 사인 URL 주소 생성]

https://kkh0977.tistory.com/8151

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


[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