728x90

요금 확인 

요금이 발생한 경우 아래 문서를 참고해서 요금 면제 신청하세요.

http://awsblogskr.s3-ap-northeast-2.amazonaws.com/aws-educate-for-student.pdf



불필요한 리소스 정리

Elastic Transcoder 



EC2 > Auto Scaling 그룹

 

EC2 > 로드 밸런서

 

EC2 > Target groups

 

EC2 > AMI



EC2 > 인스턴스

실행 중인 인스턴스 모두 중지

exercise-instance 인스턴스는 3월 19일 이후에 삭제하세요.



EC2 > Elastic Block Storage > 스냅샷



CloudWatch > 로그 > 로그 그룹








지난 주에 했던 내용(범위)

 



IAM 사용자

  • 사용자, 어플리케이션, 서비스를 식별하는 AWS의 객체
    • 서비스 계정(service account)

. 어플리케이션 또는 서비스를 대신해 작업하도록 만든 IAM 사용자

. 액세스 키를 사용해서 AWS 서비스 API에 접근할 수 있음

  • (1) 사용자를 확인하는데 도움을 주는 친숙한 이름과 (2) AWS에서 사용자를 고유하게 식별하는 ARN(Amazon Resource Name)을 가짐

  • 일반적으로 사용자는 AWS에서 자원 및 서비스에 접근하는데 사용할 수 있는 인증서 및 권한 집합을 갖고 있음



lambda-upload 사용자로 콘솔 로그인이 가능하도록 설정



다중 요소 인증 설정



그룹(P79)

  • IAM 사용자 모음
  • 여러 사용자에 대해 사용 권한을 한번에 지정할 수 있는 방법을 제공
  • AWS에서는 사용자별로 권한을 정의하는 대신 그룹을 사용해 IAM 사용자에게 권한을 할당할 것을 권장
  • 그룹에 속한 모든 사용자는 그룹에 할당된 권한을 상속 받음

 

lambda-upload 사용자에게 할당된 권한을 Lambda-DevOps 그룹을 이용해서 제공

#1 Lambda-DevOps 그룹 생성



 

#2 Lambda-DevOps 그룹에 권한을 설정

 

 

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Sid": "Stmt1451465505000",

            "Effect": "Allow",

            "Action": [

                "lambda:GetFunction",

                "lambda:UpdateFunctionCode",

                "lambda:UpdateFunctionConfiguration"

            ],

            "Resource": [

                "arn:aws:lambda:*"

            ]

        }

    ]

}



#3 lambda-upload 사용자에게 부여된 권한을 삭제





#4 Lambda-DevOps 그룹에 lambda-upload 사용자를 추가

 



역할(role) (P82)

  • 일정 기간 동안 사용자, 어플리케이션, 서비스가 맡을 수 있는 권한 집합
  • 특정 사용자에게 유일하게 결합되지 않고, 암호나 액세스 키와 같은 자격 증명도 없음
  • 일반적으로 필요한 리소스에 접근할 수 없는 사용자 또는 서비스에 권한을 부여하도록 설계되어 있음 ⇒ 예: 람다 함수가 S3에 접근할 수 있도록 역할을 생성

 

위임(delegation)

  • 특정 자원에 대해 접근할 수 있도록 제3자에게 권한을 부여하는 것
  • 자원을 소유하고 있는 신뢰를 제공하는 계정(trusting account)과 자원에 접근이 필요한 사용자 또는 어플리케이션을 포함한 신뢰를 제공받는 계정(trusted account) 간에 신뢰 관계(trust relationship)를 설정하는 작업

 

Delegation is an important concept associated with roles. Put simply, delegation is concerned with the granting of permissions to a third party to allow access to a particular resource. It involves establishing a trust relationship between a trusting account that owns the resource and a trusted account that contains the users or applications that need to access the resource. Figure 4.6 shows a role with a trust relationship established for a service called CloudCheckr, which you can read more about in section 4.3.2. 

연동(federation)

  • 페이스북, 구글과 같은 외부 자격 증명 공급자 또는 SAML(Security Assertion Markup Language) 2.0 및 AWS를 지원하는 기업용 자격 증명 시스템 간에 신뢰 관계를 생성하는 프로세스 
  • 사용자는 외부 자격 증명 공급자를 통해 로그인하고 임시 자격 증명을 갖는 IAM 역할을 맡을 수 있음

 

AWS의 권한(P83)

  • 자격 증명 기반 권한(identity-based permissions)
    • IAM 사용자 또는 역할이 수행할 수 있는 것을 지정
  • 자원 기반 권한(resource-based permissions)
    • S3 버킷, SNS 주제와 같은 AWS 자원에서 수행할 수 있는 것 또는 누가 그 자원에 접근할 수 있는지를 지정
    • 주어진 자원에 접근할 수 있는 사용자를 지정
    • S3 버킷, SNS 주제, SQS 큐, Glacier 볼트, OpsWorks 스택, Lambda 함수 등의 서비스만 자원 기반 정책을 제공

 

권한과 정책(permissions, policies)

  • 사용자, 그룹, 역할이 수행할 수 있는 작업을 기술하는 정책을 생성해 권한을 부여
  • 정책 유형 ⇒ 관리형 정책, 인라인 정책
    • 관리형 정책(managed plicies)
      • 사용자, 그룹, 역할에는 적용되지만 자원에는 적용되지 않음
      • 재사용, 변경관리, 버전관리, 롤백이 용이
    • 인라인 정책(inline policies)
      • 특정 사용자, 그룹, 역할에 직접 생성하고 적용
      • 엔티티가 삭제되면 엔티티에 적용된 인라인 정책도 삭제
      • 자원 기반 정책은 항상 인라인 정책임



{

  "Version": "2012-10-17", ⇐ 정책 언어 버전

  "Statement": [ ⇐ 정책 구문 → 정책을 구성하는 실제 권한을 지정

    {

      "Sid": "Stmt1451465505000",

      "Effect": "Allow", ⇐ 구문이 자원에 대한 접근 허용 또는 거부를 지정

      "Action": [ ⇐ 자원에 허용되거나 거부되어야 하는 특정 작업을 지정

        "lambda:GetFunction",

        "lambda:UpdateFunctionCode",

        "lambda:UpdateFunctionConfiguration"

      ],

      "Resource": [ ⇐ 구문이 적용되는 객체를 식별

        "arn:aws:lambda:*"

      ], 

 

       "Condition": { ⇐ 해당 정책을 적용할 조건을 명시 

           "DateLessThan": {          

               "aws:CurrentTime": "2016-10-12T12:00:00Z"

           }, 

           "IpAddress": {

               "aws:SourceIp": "127.0.0.1"

           }

       }

 

    }

  ]

}

 

https://docs.aws.amazon.com/ko_kr/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html




로깅 및 경고(P86)

 





프리티어 사용량 알림 수신 설정(P98)

 




 

 

 

 

 

 

 




Stateful 경우 ⇒ 일반적인 웹 서버 ⇒ 클라이언트의 상태 정보를 서버가 유지 ⇒ 세션을 이용해서 구현

Stateless 경우 ⇒ 서버로부터 발급 받은 토큰을 이용해서 신분을 증명

 

서버리스 환경에서의 인증(P108)

Amazon Cognito, Auth0, 위임 토큰 등으로 구현 가능

인증 ⇒ Cognito, Auth0 

서비스 간 사용자 정보 교환 ⇒ JWT(JSON Web Token)





24-Hour Video 사이트에 로그인/로그아웃, 사용자 프로필 기능을 추가

 

계획

  1. 로그인, 로그아웃, 사용자 프로필 버큰을 포함한 기본 웹 사이트를 생성
  2. Auth0 이용해서 어플리케이션을 등록하고 웹 사이트에 통합 → 사용자가 Auth0를 통해 로그인하고 이를 식별하는 JSON 웹 토큰을 받을 수 있어야 함
  3. 웹 사이트에서 람다 함수를 호출할 수 있도록 API Gateway를 추가
  4. user-profile 람다 함수를 생성 
  5. user-profile 람다 함수를 호출할 수 있도록 API Gateway를 구성
  6. JWT 유효성 검사를 수행하도록 API Gateway를 수정



24-Hour Video 웹 사이트 제작

#1 프로젝트 생성

PS C:\Users\i> cd C:\serverless\

PS C:\serverless> mkdir 24-hour-video

PS C:\serverless> cd .\24-hour-video\

PS C:\serverless\24-hour-video> npm init -y

PS C:\serverless\24-hour-video> npm install local-web-server --save-dev

 

#2 Visual Studio Code 실행해서 start 스크립트 추가

c:\serverless\24-hour-video\package.json

{

  "name": "24-hour-video",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "start": "ws"

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "devDependencies": {

    "local-web-server": "^4.2.1"

  }

}

 

참고: local-web-server ⇒ https://www.npmjs.com/package/local-web-server

 

#3 UI 템플릿 다운로드

http://www.initializr.com/



#4 다운로드 받은 템플릿 파일을 프로젝트 폴더로 압축 해제

 

#5 웹 서버를 실행하고 확인

PS C:\serverless\24-hour-video> npm start

 

> 24-hour-video@1.0.0 start C:\serverless\24-hour-video

> ws

 

Listening on http://DESKTOP-ARFC5LS:8000, http://172.22.96.1:8000, http://172.30.1.16:8000, http://192.168.56.1:8000, http://127.0.0.1:8000, http://172.26.0.1:8000

 




Auth0 구성 (P116)

#1 https://auth0.com/ 사이트에 회원 가입

  • TENANT DOMAIN에 본인이 기억할 수 있는 이름을 입력
  • REGION을 US로 설정
  • ACCOUNT TYPE은 Personal로 설정

 




#2 Application 생성



 



#3 Google Cloud Platform에 사용자 인증 정보를 추가

https://console.cloud.google.com

 

#3-1 프로젝트 생성

 



#3-2 OAuth 동의 화면 생성



 

 

이후부터로 디폴트 상태에서 [저장 후 계속]으로 진행



#3-3 사용자 인증 정보 생성

 

#4 Auth0에 Social Connection으로 Google을 추가하고 테스트 



 

GCP에서 사용자 인증 정보 생성을 통해서 만들어진 Client ID와 Client Secret를 입력

 

 




#5 Facebook for Developers 사이트에서 Facebook 로그인 앱 추가

https://developers.facebook.com/apps/



 



#6 Auth0에 Social Connection으로 Facebook 추가 및 테스트 

 

 








웹 사이트에 Auth0를 연결(P119)

 

#1 Auth0 Lock 스크립트, Domain, Client ID를 확인

 





#2 Auth0 Lock 스크립트 및 로그인/로그아웃/프로필 버튼을 추가

   ~~~~~~~~~~~~~ ⇒ 로그인, 회원가입 등의 대화상자를 제공하는 Auth0의 무료 위젯

 

c:\serverless\24-hour-video\index.html

                :

        <div id="navbar" class="navbar-collapse collapse">

          <div class="navbar-form navbar-right">

            <button id="user-profile" class="btn btn-default">

              <img id="profilepicture" />&nbsp;<span id="profilename"></span>

            </button>

            <button id="auth0-login" class="btn btn-success">Sign in</button>

            <button id="auth0-logout" class="btn btn-success">Sign out</button>

          </div>

          <!--

          <form class="navbar-form navbar-right" role="form">

            <div class="form-group">

              <input type="text" placeholder="Email" class="form-control">

            </div>

            <div class="form-group">

              <input type="password" placeholder="Password" class="form-control">

            </div>

            <button type="submit" class="btn btn-success">Sign in</button>

          </form>

          -->

        </div><!--/.navbar-collapse -->

                :

                :

        <script src="js/vendor/bootstrap.min.js"></script>

        

        <script src="js/user-controller.js"></script>

        <script src="js/config.js"></script>

        <script src="js/main.js"></script>


        <script src="js/main.js"></script>

                :

 





c:\serverless\24-hour-video\js\user-controller.js

// userController 객체를 선언

var userController = {

    data: {

        auth0Lock: null,

        config: null

    }, 

    // HTML 문서에서 제어할 요소들(버튼, 이미지, 라벨, ... 등)

    uiElements: {

        loginButton: null,

        logoutButton: null, 

        profileButton: null, 

        profileNameLabel: null,

        profileImage: null

    }, 

    // 설정 정보와 제어할 요소들을 초기화

    init: function (config) {

        var that = this;

 

        // HTML 문서에서 id 속성의 값이 auth0-login인 요소를 가져와서 loginButton 변수에 할당

        // <button id="auth0-login" class="btn btn-success">Sign in</button>

        this.uiElements.loginButton = $('#auth0-login');

        this.uiElements.logoutButton = $('#auth0-logout');

        this.uiElements.profileButton = $('#user-profile');

        this.uiElements.profileNameLabel = $('#profilename');

        this.uiElements.profileImage = $('#profilepicture');

 

        // config.js의 포함되어 있는 설정 정보를 변수에 할당

        this.data.config = config;

 

        this.data.auth0Lock = new Auth0Lock(config.auth0.clientId, config.auth0.domain);

        

        this.configureAuthenticatedRequests();

        

        // 로컬 스토리지에 accessToken이 존재하면 

        var accessToken = localStorage.getItem('accessToken');

        if (accessToken) {

            // 사용자의 프로필을 조회

            this.data.auth0Lock.getProfile(accessToken, function (err, profile) {

                if (err) {

                    return alert('프로필을 가져오는데 실패했습니다. ' + err.message);

                }

                // 사용자 프로필 조회에 성공하면 프로필 정보를 showUserAuthenticationDetails 함수로 전달

                that.showUserAuthenticationDetails(profile);

            });

        }

        // 이벤트 핸들러를 정의

        this.wireEvents();

    },

    // 로컬 스토리지에 저장된 idToken, accessToken을 Authorization, AccessToken 요청 헤더의 값으로 설정

    // => 요청 헤더의 값으로 설정되려면, 로컬 스토리지에 해당 값들이 존재해야 함

    configureAuthenticatedRequests: function() {

        $.ajaxSetup({

            'beforeSend': function (xhr) {

                console.log(xhr);

                xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('idToken'));

                xhr.setRequestHeader('AccessToken', localStorage.getItem('accessToken'));

            }

        })

    }, 

    // 전달받은 프로필 정보를 사용자 화면에 출력

    showUserAuthenticationDetails: function(profile) {

        // 프로필 정보 여부를 참, 거짓으로 설정

        // profile 변수가 null, undefined, ''인 경우 ==> false를 할당

        // profile 변수가 값이 있는 경우 ==> true를 할당

        var showAuthenticationElements = !!profile;



        // 프로필 정보가 존재하면 사용자 이름과 사진을 출력

        if (showAuthenticationElements) {

            this.uiElements.profileNameLabel.text(profile.nickname);

            this.uiElements.profileImage.attr('src', profile.picture);

        }

        // 프로필 정보가 존재하면 로그인 버튼을 감추고, 로그아웃 버튼과 프로필 버튼을 나타나게 처리

        this.uiElements.loginButton.toggle(!showAuthenticationElements);

        this.uiElements.logoutButton.toggle(showAuthenticationElements);

        this.uiElements.profileButton.toggle(showAuthenticationElements);

    }, 

    // 특정 이벤트에 반응하는 함수를 정의

    wireEvents: function() {

        var that = this;

 

        // auth0 lock에서 제공하는 로그인 창에서 authenticated 이벤트가 발생하는 경우 

        // 수행할 함수를 정의

        this.data.auth0Lock.on('authenticated', function(authResult) {

            // 로그인에 성공하면 accessToken, idToken 값을 로컬 스토리지에 저장

            console.log(authResult);

            localStorage.setItem('accessToken', authResult.accessToken);

            localStorage.setItem('idToken', authResult.idToken);

 

            // 로그인에 성공하면 사용자 정보를 조회

            that.data.auth0Lock.getUserInfo(authResult.accessToken, function (error, profile) {

                // 사용자 정보 조회에 성공하면 반환받은 profile 정보를 showUserAuthenticationDetails 함수로 전달

                if (!error) {

                    that.showUserAuthenticationDetails(profile);

                }

            });

        });



        // 로그인 버튼을 클릭했을 때 처리 -> auth0 lock에서 제공하는 로그인 화면을 실행

        this.uiElements.loginButton.click(function(e) {

            that.data.auth0Lock.show();

        });



        // 로그아웃 버튼을 클릭했을 때 처리 

        //  -> 로컬 스토리지에 저장된 accessToken, idToken을 삭제

        //  -> 로그 아웃, 프로필 버튼을 숨기고, 로그인 버튼을 나타나게 처리

        this.uiElements.logoutButton.click(function(e) {

            localStorage.removeItem('accessToken');

            localStorage.removeItem('idToken');

            that.uiElements.logoutButton.hide();

            that.uiElements.profileButton.hide();

            that.uiElements.loginButton.show();

        });

    }

};

 



c:\serverless\24-hour-video\js\config.js

var configConstants = {

    auth0: {

        domain: '본인의AUTH0의도메인',

        clientId: '본인의AUTH0의클라이언트ID'

    }

};

 

c:\serverless\24-hour-video\css\main.css

#auth0-logout {

  display: none;

}

#user-profile {

  display: none;

}

#profilepicture {

  height: 20px;

  width: 20px;

}

 

c:\serverless\24-hour-video\js\main.js

// 즉시 실행 함수

(function() {

    // 해당 웹 페이지 문서가 로딩되면 설정 정보를 가져와서 설정

    $(document).ready(function() {

        // user-controller.js에 선언되어 있는 userController 객체의 init 메소드를 호출

        // coonfig.js에 선언되어 있는 configConstants 객체를 인자로 전달

        userController.init(configConstants);

    });

})();

 



Auth0 Lock API Reference

https://auth0.com/docs/libraries/lock/lock-api-reference



로그인에 성공하면 아래와 같이 프로필과 로그아웃 버튼이 출력

 

728x90

'CLOUD > AWS' 카테고리의 다른 글

3/17 - AWS 14차시  (1) 2021.03.17
3/16 - AWS 13차시  (0) 2021.03.16
3/12 - AWS 11차시  (0) 2021.03.12
3/11 - AWS 10차시  (0) 2021.03.11
3/10 - AWS 9차시  (0) 2021.03.10

+ Recent posts