GAM309 Breathe life into a Mobile Game Lab 1

18 downloads 163 Views 1MB Size Report
In this lab, you will implement the authentication using several AWS Managed services such as Amazon Cognito, ... App client name: AWSShooter. ▫ Check Enable sign-in API for server-based authentication ..... 5.1.1 Click the Shooter executable file that you downloaded and unzipped before. 5.1.2 Click Play! button (Screen ...
GAM309 Breathe life into a Mobile Game Lab 1 (Limited use only)

© 2017 Amazon Web Services, Inc. or its affiliates. All rights reserved. This work may not be reproduced or redistributed, in whole or in part, without prior written permission from Amazon Web Services, Inc. Commercial copying, lending, or selling is prohibited. Corrections or feedback on the lab guide, please email me at: [email protected]. All trademarks are the property of their owners.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

2

Index Lab 1-1. Authentication with Amazon Cognito

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

3

Lab 1-1 Authentication with Amazon Cognito Overview In this lab, you will implement the authentication using several AWS Managed services such as Amazon Cognito, Amazon DynamoDB and AWS Lambda. In this lab, you will setup an Amazon Cognito User Pool and Amazon Cognito Identity Pool to allow users to register to the demo game and get a temporary credentials.

Objectives After completing this lab, you will be able to: ▪

Create an Amazon Cognito User Pool to allow users to sign up and sign in



Access to AWS services securely



Share user data across client platforms, devices, and operating systems



Share user data in the Amazon Cognito Sync Store



Setup an Amazon DynamoDB table for user profile

Pre-requisites This lab requires: ▪

Access to a notebook computer with Wi-Fi running Microsoft Windows or Mac OS X



For Microsoft Windows users: Administrator access to the computer



An internet browser such as Chrome, Firefox, or Internet Explorer 10

Duration 40 minutes

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

4

Task 1: Create an Amazon Cognito User Pool for user directory Overview Amazon Cognito User pool allows us to manage our own user directory. This service is fully managed service. Create an Amazon Cognito User Pool that allows users to register to the demo game. Notice) Please ensure US East (N. Virginia) is selected for the region. Notice) We proceed only with the minimum settings required for smooth lab progress. In an actual service environment, it is highly recommended to set more precisely such things as access control.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

5

Task 1.1: Creating an Amazon Cognito User Pool Overview In this section, you will create an Amazon Cognito User Pool. A User Pool is your user directory that you can configure for your games. A User Pool securely stores your users’ profile attributes and also it allows users in the pool to access AWS resources securely by integrating with Amazon Cognito Federated Identities. 1.1.1 Login to the AWS Management Console and choose Services  Mobile Services  Cognito. 1.1.2 Click Manage your User Pools. 1.1.3 Click Create a user pool button. 1.1.4 Give the pool name AWSShooter and click Step Through settings.

1.1.5 Uncheck the email under Which standard attributes do you want to require and click the Next step button.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

6

1.1.6 Put 6 to the Minimum length field and uncheck all the checkboxes under the Minimum length field (Require numbers/special character/uppercase letters/lowercase letter) and click the Next step button.

1.1.7 Uncheck Email under Do you want to require verification of emails or phone numbers? and click the Next step button.

1.1.8 Click the Next step button on Message customizations page. 1.1.9 Click the Next step button on Tags page. 1.1.10 Click No and click the Next step button.

1.1.11 Click Add an app client and configure according to below: ▪

App client name: AWSShooter



Check Enable sign-in API for server-based authentication (ADMIN_NO_SRP_AUTH)

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

7

1.1.12 Click Create app client. 1.1.13 Click the Next step button on App clients page.

1.1.14 Click the Next step button on Triggers page and click the Create pool button in the Review stage. 1.1.15 Copy and paste the Pool Id and Pool ARN to Notepad, so that we will use later for the demo game.

1.1.16 Click App clients on the left panel.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

8

1.1.17 Copy and paste the App client id and App client secret to Notepad.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

9

Task 1.2: Creating an Amazon Cognito Identity Pool Overview In this section, you will create an Amazon Cognito Identity Pool. An identity pool is a store of user identity data specific to your account. With an identity, you can obtain temporary, limited-privilege AWS credentials to synchronize data with Amazon Cognito Sync, or directly access other AWS services. 1.2.1 Login to the AWS Management Console and choose Services  Mobile Services  Cognito. 1.2.2 Click Manage Federated Identities. 1.2.3 Click Create a new identity pool button or you will see Getting started wizard if this is the first time you use it. 1.2.4 Name the identity pool as AWSShooter.

1.2.5 Extend Authentication providers and fill the input fields with below: ▪

User Pool ID: Paste your User Pool ID that we created in the task 1.1, which will look like us-east-1_SAMPLE.



App client id: Paste your app client id that we created in the task 1.1, which will look like 77od5dmcdfakshnb59i4gaeeo1.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

10

1.2.6 Click Create Pool. 1.2.7 In the creating IAM role page, click View Details. 1.2.8 Name the role for authenticated identities AWSShooter-Cognito-AuthRole and the role for unauthenticated identities AWSShooter-CognitoUnauthRole.

1.2.9 Click Allow button. 1.2.10 The page will appear like below:

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

11

1.2.11 Copy and paste the Identity pool ID to Notepad for later use.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

12

Task 2: Confirm user registration automatically Overview When a user tries to sign up Amazon Cognito User Pool requires it to be confirmed for the further processes. In the demo game, we will make it automatically confirmed using AWS Lambda triggers provided by Amazon Cognito User Pools. The lambda function will be invoked and auto-confirm a user on sign-up. Notice) We proceed only with the minimum settings required for smooth lab progress. In an actual service environment, it is highly recommended to set more precisely such things as access control.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

13

Task 2.1: Creating a Lambda function to auto-confirm registration Overview In this section, you will create a Lambda function that confirms a user registration automatically. 2.1.1 Login to the AWS Management Console and choose Services  Compute  Lambda. 2.1.2 Click Create function button. 2.1.3 Click Author from scratch to use our own function.

2.1.4 Give the name AWSShooter-PreSignup and choose Create a custom role under the Role section. 2.1.5 In the creating IAM role for the Lambda function page, choose Create a new IAM role on the IAM role section. 2.1.6 Name the role AWSShooter-Lambda-PreSignup-Role.

2.1.7 Click Allow button. 2.1.8 Click Create function button. 2.1.9 Change Runtime from Node.js 6.10 to Python 2.7. 2.1.10 Paste below code to in lambda function code:

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

14

from __future__ import print_function import hmac import hashlib import base64 CLIENT_ID = '' CLIENT_SECRET = '' def get_secret_hash(username): msg = username + CLIENT_ID dig = hmac.new(str(CLIENT_SECRET).encode('utf-8'), msg = str(msg).encode('utf-8'), digestmod=hashlib.sha256).digest() d2 = base64.b64encode(dig).decode() return d2 def lambda_handler(event, context): event['response'] = { "autoConfirmUser": True } return event Python uses indentation instead of braces to structure its programs and scripts into blocks, which means you need to ensure that the indentation is correct. We recommend you to download the code from here and paste it. CLIENT_ID and CLIENT_SECRET should be changed and look like this: CLIENT_ID = ' 7lhlkkfbfb4q5kpp90urffao' CLIENT_SECRET = '1bbe7o8981t3olkuhp1t92ijdnqf2o4kb531u03kdnod32booega' You can find the information in App clients on the User Pool that you created before. 2.1.11 Change Timeout from 3 sec to 5 sec.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

15

2.1.12 Click Save button. 2.1.13 Click Test button and fill the text fields with below information: ▪

Event name: TestAutoConfirm



Code: { } (empty inside braces {})

2.1.14 Click Create button. 2.1.15 Click Test button again and you should find below output when you unfold Execution result details like below:

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

16

Task 2.2: Setting a trigger to invoke the Lambda function Overview In this section, you will set a trigger to invoke the Lambda function we created in the task 2.1. 2.2.1 Login to the AWS Management Console and choose Services  Mobile Services  Cognito. 2.2.2 Click Manage your User Pools. 2.2.3 Click AWSShooter that we created previously. 2.2.4 Click Triggers on the left panel.

2.2.5 On Pre sign-up, set Lambda function to the function AWSShooterPreSignup we created before.

2.2.6 Click Save changes button.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

17

Task 3: Setting up the Authentication initiator Overview Client can communicate with AWS resources using the AWS SDKs. However, it is also a good idea to use AWS Lambda as a service proxy to add additional processes. In this task, we will use Amazon API Gateway and AWS Lambda to add our own authentication processes. Notice) We proceed only with the minimum settings required for smooth lab progress. In an actual service environment, it is highly recommended to set more precisely such things as access control.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

18

Task 3.1: Creating a Lambda function that interacts with Amazon Cognito User Pool Overview In this section, we will create a Lambda function that interacts with Amazon Cognito User Pools. 3.1.1 Login to the AWS Management Console and choose Services  Compute  Lambda. 3.1.2 Click Create function button. 3.1.3 Click Author from scratch to use our own function. 3.1.4 Name the function AWSShooter-SignIn and choose Create a custom role under the Role section. 3.1.5 In the creating IAM role for the Lambda function page, choose Create a new IAM role on the IAM role section. 3.1.6 Name the role AWSShooter-Lambda-SignIn-Role. 3.1.7 Unfold Policy Document, click Edit and then edit the policy as below: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "cognito-identity:*", "cognito-idp:*", "cognito-sync:*", "iam:ListRoles", "iam:ListOpenIdConnectProviders", "sns:ListPlatformApplications" ], "Resource": "*" } ] }

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

19

3.1.8 Click Allow button. 3.1.9 Click Create function button. 3.1.10 Change Runtime from Node.js 6.10 to Python 2.7. 3.1.11 Paste below code to in lambda function code: from __future__ import print_function import boto3 import botocore.exceptions import hmac import hashlib import base64 import json import uuid # MODIFY USER_POOL_ID = '' CLIENT_ID = '' CLIENT_SECRET = '' client = None def get_secret_hash(username): msg = username + CLIENT_ID dig = hmac.new(str(CLIENT_SECRET).encode('utf-8'), msg = str(msg).encode('utf-8'), digestmod=hashlib.sha256).digest() d2 = base64.b64encode(dig).decode() return d2 ERROR = 0 SUCCESS = 1 USER_EXISTS = 2 def sign_up(username, password): try: resp = client.sign_up( ClientId=CLIENT_ID, SecretHash=get_secret_hash(username), Username=username, Password=password) print(resp) except client.exceptions.UsernameExistsException as e: return USER_EXISTS except Exception as e: print(e) return ERROR return SUCCESS def initiate_auth(username, password):

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

20

try: resp = client.admin_initiate_auth( UserPoolId=USER_POOL_ID, ClientId=CLIENT_ID, AuthFlow='ADMIN_NO_SRP_AUTH', AuthParameters={ 'USERNAME': username, 'SECRET_HASH': get_secret_hash(username), 'PASSWORD': password }, ClientMetadata={ 'username': username, 'password': password }) except client.exceptions.NotAuthorizedException as e: return None, "The username or password is incorrect" except Exception as e: print(e) return None, "Unknown error" return resp, None def lambda_handler(event, context): global client if client == None: client = boto3.client('cognito-idp') print(event) body = event username = body['username'] password = body['password'] is_new = "false" user_id = str(uuid.uuid4()) signed_up = sign_up(username, password) if signed_up == ERROR: return {'status': 'fail', 'msg': 'failed to sign up'} if signed_up == SUCCESS: is_new = "true" #user_id = str(uuid.uuid4()) resp, msg = initiate_auth(username, password) if msg != None: return {'status': 'fail', 'msg': msg} id_token = resp['AuthenticationResult']['IdToken'] print('id token: ' + id_token) return {'status': 'success', 'id_token': id_token, 'user_id': user_id, 'is_new': is_new}

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

21

Python uses indentation instead of braces to structure its programs and scripts into blocks, which means you need to ensure that the indentation is correct. We recommend you to download the code from here and paste it. USER_POOL_ID, CLIENT_ID and CLIENT_SECRET should be changed and look like this: USER_POOL_ID = 'us-east-1_testTh1ng’ CLIENT_ID = ' 7lhlkkfbfb4q5kpp90urffao' CLIENT_SECRET = '1bbe7o8981t3olkuhp1t92ijdnqf2o4kb531u03kdnod32booega' You can find the information in App clients on the User Pool that you created before. 3.1.12 Change Timeout from 3 sec to 5 sec. 3.1.13 Click Save button. 3.1.14 Click Select a test event and Configure test events.

3.1.15 Fill the text fields with below values: ▪

Event name: Authentication



Code: { "username": "tester", "password": "testpassword" }

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

22

3.1.16 Click Create button. 3.1.17 Click Test button and you can find below output when you unfold Execution result details like below:

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

23

Task 3.2: Creating an API in Amazon API Gateway Overview In this section, we will create an API in Amazon API Gateway as a proxy for AWS Lambda that interacts with Amazon Cognito User Pools. 3.2.1 Login to the AWS Management Console and choose Services  Application Services  API Gateway. 3.2.2 Click Create API. 3.2.3 Name the API AWSShooter and click Create API.

3.2.4 Click Actions and Create Resource.

3.2.5 Name the resource as authenticate and click Create Resource button.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

24

3.2.6 Click Actions and Create Method.

3.2.7 Choose POST and click the Check button.

3.2.8 Choose us-east-1 for Lambda Region and AWSShooter-SignIn for Lamda Function.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

25

3.2.9 Click Save button and OK button on the Add Permission to Lambda Function dialog. 3.2.10 Click TEST button on the left.

3.2.11 Put below to the Request Body form: { "username":"tester", "password":"testpassword" }

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

26

3.2.12 Click Test button and it will look like this:

3.2.13 Click Actions and Deploy API.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

27

3.2.14 Name the stage as Prod and click Deploy.

3.2.15 Copy and paste the Invoke URL to Notepad.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

28

Task 4: Create a DynamoDB Table to store user profile Overview Amazon DynaomDB is a great service to store data with expected performance. In this section, you will create a DynamoDB table and store user profile that is created from the game client. Notice) We proceed only with the minimum settings required for smooth lab progress. In an actual service environment, it is highly recommended to set more precisely such things as access control.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

29

Task 4.1: Creating a DynamoDB Table Overview In this section, you will create a DynamoDB table and assign table structure to store user profile. 4.1.1 Login to the AWS Management Console and choose Services  Database  DynamoDB. 4.1.2 Click Create table button. 4.1.3 Name the table AWSShooter-UserProfile. 4.1.4 Name the partition key user_id with type string. 4.1.5 Click Create to create a table. 4.1.6 On the dashboard, you will see the table being created for you. This will take a few moments.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

30

Task 4.2: Attaching an additional policy to Cognito Authenticated Role Overview In this section, you will attach an additional policy to Cognito Authenticated identity role to communicate with Amazon DynamoDB. 4.2.1 Login to the AWS Management Console and choose Services  Security, Identity & Compliance  IAM. 4.2.2 Click Roles on the left panel.

4.2.3 Click AWSShooter-Cognito-AuthRole.

4.2.4 Click Attach policy button.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

31

4.2.5 Search DynamoDB and check AmazonDynamoDBFullAccess.

4.2.6 Click Attach policy button.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

32

Task 5: Set up the demo game to work Overview Configure the demo game to sign up and sign users from the demo game. Notice) We proceed only with the minimum settings required for smooth lab progress. In an actual service environment, it is highly recommended to set more precisely such things as access control.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

33

Task 5.1: Editing Sign-In URL, Amazon Cognito User Pool ID and Identity Pool ID Overview In this section, we will configure the demo game with Amazon Cognito User Pool ID and Identity Pool ID. 5.1.1 Click the Shooter executable file that you downloaded and unzipped before. 5.1.2 Click Play! button (Screen resolution depends on your preferences).

5.1.3 Press F1 key on your keyboard to configure and fill the text input fields with below information: ▪

Assets URL: http://d2gfzxspanloyo.cloudfront.net/list/assets.json



Sign-In URL: Paste the invoke URL on API Gateway with adding /authenticate at the end, which will look like https://testhashvalue.execute-api.us-east1.amazonaws.com/Prod/authenticate



Identity Pool: Paste your Identity pool ID that we created in the task 2, which will look like us-east-1:413cb547-42x8-691a-a165-651171e1df9c.



User Pool: Paste your User pool ID that we created in the task 1, which will look like us-east-1_SAMPLE.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

34

5.1.4 Click Reset button. 5.1.5 Put a username and password and click SIGN IN! button. In the lab guides, aws (username) and reinvent (password) will be used. 5.1.6 You can see PLAY! button with messages appeared on the upper left on the play screen.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

35

Task 5.2: Confirming working Amazon Cognito Overview In this section, we will see if sign-up and sign-in users works or not. 5.2.1 Login to the AWS Management Console and choose Services  Mobile Services  Cognito. 5.2.2 Click Manage your User Pools. 5.2.3 Click AWSShooter that we created before. 5.2.4 Click Users and groups on the left panel. 5.2.5 You will see two registered users, one was registered when we tested the Lambda function and the other one was registered when we signed in in the game. If nothing is showing up, click Refresh icon on the right upper corner.

5.2.6 Click Federated Identities on the top of the page and click AWSShooter that we created before.

5.2.7 When you click Identity browser on the left panel, you can find an identity ID that was created when we signed in in the game.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

36

5.2.8 Click the identity ID that is for whom was registered in the demo game. 5.2.9 You can see the dataset named UserProfile. Once you click the dataset, you can find two values like below:

5.2.10 Play the game awhile (at least 10 seconds) and then refresh the dataset. You can find the changed values. When you restart the game, you can also find the score and the character’s starting position has changed according to the values of the dataset.

© 2017 Amazon Web Services, Inc. or its affiliates All rights reserved.

37