GithubHelp home page GithubHelp logo

amazon-archives / aws-serverless-auth-reference-app Goto Github PK

View Code? Open in Web Editor NEW
754.0 84.0 193.0 3.17 MB

Serverless reference app and backend API, showcasing authentication and authorization patterns using Amazon Cognito, Amazon API Gateway, AWS Lambda, and AWS IAM.

License: Other

JavaScript 39.89% TypeScript 48.56% CSS 1.34% HTML 8.77% Shell 0.52% Dockerfile 0.91%
amazon-cognito aws-cognito serverless iam serverless-architectures aws-lambda cognito cognito-quickstart authentication authorization

aws-serverless-auth-reference-app's Introduction

SpaceFinder - Serverless Auth Reference App

SpaceFinder is a reference mobile app that allows users to book conference rooms, work desks, and other shared resources. The app showcases serverless authentication and authorization using the AWS platform.

The mobile front-end is built using the Ionic 3 framework and client libraries to call AWS services and mobile backend APIs. The backend APIs themselves are powered by AWS services. The backend APIs are built using a serverless architecture, which makes it easy to deploy updates, and it also means that there are no servers to operationally manage.

SpaceFinder is primarily developed and maintained by Jim Tran and Justin Pirtle, Solutions Architects at Amazon Web Services. The project code is released under the Apache 2.0 license. Please feel free to make use of the code in this project, and spread the word. We hope you enjoy it, and we certainly welcome all feedback, pull requests and other contributions!

Video presentation

A live demo of the SpaceFinder app was presented at AWS re:Invent 2017, the annual AWS cloud computing conference. The presentation provides useful context on the authentication and authorization flows that the app demonstrates. The YouTube recording of the session (53 minutes) is available here:

Quickstart and Developer Guide

  1. The Quickstart guide walks through setting up a demo environment (5 minutes) with a tutorial of key app flows (30 minutes). This lab is self-contained and cleans up after itself by un-deploying all auto-generated AWS resources.

  2. For developers who want to dig deeper, we've also prepared a Developer Guide. The Developer Guide provides instructions on setting up the project pre-requisites manually in your developer environment.

Architecture diagram

Spacefinder Mobile App architecture

AWS services used

SpaceFinder is built using the following AWS services:

  • AWS Cognito - Amazon Cognito lets you easily add user sign-up and sign-in to your mobile and web apps. With Amazon Cognito, you also have the options to authenticate users through social identity providers such as Facebook, Twitter, or Amazon, with SAML identity solutions, or by using your own identity system. Furthermore, AWS Cognito supports User Groups that let to create collections of users to manage their permissions or to represent different types of users.
  • AWS Lambda - AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration.
  • Amazon DynamoDB - Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models.
  • Amazon API Gateway - Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. You can create an API that acts as a “front door” for applications to access data, business logic, or functionality from your back-end services, such as workloads running on Amazon Elastic Compute Cloud (Amazon EC2), code running on AWS Lambda, or any Web application. Amazon API Gateway handles all the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, authorization and access control, monitoring, and API version management.
  • AWS CloudFormation - AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.

Backend API

Spacefinder uses a Serverless API built using Amazon API Gateway, Lambda, DynamoDB, and CloudFormation. The API has the following REST methods, and some methods can only be called by users with "Admin" privileges.

Spacefinder API

Mobile app

The mobile app is a hybrid mobile app, and is built on the Ionic 3 framework, which relies on Angular 4 and TypeScript 2. The hybrid mobile app can run on Android devices and iOS devices, as well as a modern web browser.

Spacefinder Mobile app

User flows

The app currently demonstrates the following user flows:

  • Identity Management
    • Register as a new user
    • Confirm registration code
    • Sign in (as a user who has already confirmed a registration code)
    • Sign in (as a user who has not yet confirmed a registration code)
    • Re-send registration code
    • Forgot password
    • Change password
    • Sign-out
  • SpaceFinder Application Features
    • View list of locations
    • Add a new location (Admin-only feature)
    • Delete a location (Admin-only feature)
    • View list of resources at a location
    • Add a new resource (Admin-only feature)
    • Delete a resource (Admin-only feature)
    • View resource availability
    • Book a new booking
    • Cancel own booking
    • Cancel another user's booking (Admin-only feature)
    • Upload a profile image to Amazon S3
    • Toggle display of admin-only features

Using the app

Sample users and data

Sample users and location/resource data are created as part of the bootstrapping process, to make it easy for you to try out the user flows. Use the following users to login to the application. You may additionally create your own personal accounts.

  • Standard user

    • Username: user1
    • Password: Test123!
    • Can browse resources, make bookings, and upload profile picture
  • Admin user

    • Username: admin1
    • Password: Test123!
    • Can additionally create and delete locations and resources

Console logging

Enable the browser developer console (or remote debugging for Android) to view all of the log messages.

The log messages will show you all tokens retrieved as part of the sign-in process, as well as all API calls made and the corresponding authorization for each call.

aws-serverless-auth-reference-app's People

Contributors

eranation avatar jtran21 avatar justonian avatar ovalba avatar proximitorerin avatar tkushagr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-serverless-auth-reference-app's Issues

Login with facebook/Google

i am wondering how do i setup logging in with facebook or google with cognito and setting it up profiles, will there be an update on this in the near future?
Thanks

Side menu version

I am having trouble switching from the tab version to a side menu version. Has anyone created a side menu version and could post the code or instructions? Thanks in advance.

Gulp Deploy - ValidationError (create_cloudformation_stack)

So far the steps in this Setup section of lab have worked without issue, but when running gulp deploy in Step 4, I am bumping into something I have not been able to resolve.

I am receiving the following error:

create_cloudformation_stack' errored after 279 ms
[17:41:15] ValidationError: Stack:arn:aws:cloudformation:us-east-1:123456789018:stack/spacefinder-api-development-stack/632a29c13zfe is in CREATE_FAILED state and can not be updated.

Things I have tried so far:

  • Run through the steps a few times.
  • Double checked the credentials are correct (key & secret in aws configure).
  • Made sure the IAM user has admin privileges.

Where do I set credentials for deployment?

Where should I set credentials for the deployment? I followed all the install steps for the API and am now trying to run "gulp deploy", getting a "missing credentials error". Console output:

paulfryer:~/workspace/api (master) $ gulp deploy
[01:47:53] Using gulpfile ~/workspace/api/gulpfile.js
[01:47:53] Starting 'deploy'...
[01:47:53] Starting 'create_cloudformation_stack'...
[2016-12-18T01:47:53.628Z] INFO: spacefinder/2703 on paulfryer-serverless-4171287: Creating CloudFormation stack...
[2016-12-18T01:47:54.678Z] ERROR: spacefinder/2703 on paulfryer-serverless-4171287:
step failed { [CredentialsError: Missing credentials in config]
message: 'Missing credentials in config',
code: 'CredentialsError',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: Sun Dec 18 2016 01:47:54 GMT+0000 (UTC),
originalError:
{ message: 'Could not load credentials from any providers',
code: 'CredentialsError',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: Sun Dec 18 2016 01:47:54 GMT+0000 (UTC),
originalError:
{ code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
message: 'connect ECONNREFUSED 169.254.169.254:80' } } }
[01:47:54] 'create_cloudformation_stack' errored after 1.05 s
[01:47:54] Error: connect ECONNREFUSED 169.254.169.254:80
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)
[01:47:54] 'deploy' errored after 1.2 s

Account Image is not persisted

The account image is not loaded if you load the app again. It is persisted to s3 but I do not see anything that actually persists the URL for future use. If you attach a profile image and then logout and reload the app and login. The profile image shows it is unset.

Could you provide some sample Java code for Cognito UserPool Authorizer client

This is from the generated java SDK

import com.amazonaws.ImmutableRequest;

import spacefinder.auth.SpacefinderUserPoolAuthorizer;

public class SpacefinderUserPoolAuthorizerImpl implements SpacefinderUserPoolAuthorizer {

	@Override
	public String generateToken(ImmutableRequest<?> request) {
		return "some-generated-auth-token";
	}
}

Obviously, there is a big gap between "some-generated-auth-token" and a working Authorizer client.
We want to use Cognito User Pools + Cognito Federated Identities + Amazon API Gateway to create an API for third party developers.
I really appreciate the help.

POST error while booking a resource

I am facing this error while booking a resouce
POST https://5av9drf8dr.execute-api.us-east-1.amazonaws.com/development/users/us-east-1_10fvdgc6-d94c-4970-94bt-c3a94690tb1b/bookings 500 (Internal Server Error)

regenerating sdk causes issues

I am working on customised version of this app, but the same thing is observed with latest version of current app. The problem is when I try to generate sdk with gulp generate_sdk, the code generated is very different than committed code.

For example diff for a line in file app/src/services/spacefinder-sdk/api/DefaultApi.ts:

-    constructor(protected http: Http, @Optional() basePath: string) {
+    constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {

These 'extra' changes causes further problems - like it should be basePath?: string and not basepath: string, and so on.

My question is - how can we generate a consistent API with command gulp generate_sdk with no unnecessary additions?

api create_sdk command fails

The create_sdk command fails with the error below. I did not see swagger included in the node packages. What is the expectation here?

[22:04:11] Error: spawn swagger-codegen ENOENT at exports._errnoException (util.js:1022:11) at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32) at onErrorNT (internal/child_process.js:359:16) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) at Module.runMain (module.js:606:11) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3

Vendor script reference seems to be missing (webpackjsonp is not defined)

Hello,

First of all let me tell you that this lab rocks, it's simply awesome and very helpfull.

I'm new developing on this platform (Angular, Ionic & AWS) and I just want to share with you the problem I had before I could be able to run through the application.

I followed the steps in the Developer Guide to setup my local environment, and when I tried to load the application the response in the web browser was:

**Runtime Error**
webpackjsonp is not defined

**Stack**
@http://localhost:8100/build/main.js:1:1

Ionic Framework: 2.0.0-rc.1
Ionic Native: 2.2.3
Ionic App Scripts: 2.0.2
Angular Core: 2.0.0
Angular Compiler CLI: 0.6.2
Node: 6.11.1
OS Platform: Linux 4.8
Navigator Platform: Linux x86_64
User Agent: Mozilla/5.0

After some time searching on the forums I found out that the script reference to vendor.js was missing in the index.html, so I added the missing reference bellow the polyfills.js line:

<script src="build/polyfills.js"></script>
<script src="build/vendor.js"></script>

After that the application started working as expected.

Best regards

Friends List inside User Pools?

I want to create a friends section in it, Is it a good method to create a a friends attribute inside Cognito User Pool Id, or do i need to make use of profiles table in DynamoDB and access its data and create friends list in return.

TypeError: AppScripts.serve is not a function

Receiving error "TypeError: AppScripts.serve is not a function" when running cmd ionic serve.

To fix the error change app/package.json line 37 @ionic/app-scripts: 1.0.0 to 1.1.4 then run npm install again.

Cannot run gulp deploy

Hi!

I am trying to follow through the instructions at https://github.com/awslabs/aws-serverless-auth-reference-app/blob/master/Quickstart.md.

I got to the point where I have to run gulp deploy and I get the following error:

[2017-12-23T12:54:27.182Z] INFO: spacefinder/96 on a032005c04ce: Creating CloudFormation stack...
[2017-12-23T12:54:27.731Z] ERROR: spacefinder/96 on a032005c04ce:
step failed { Error: getaddrinfo EAI_AGAIN cloudformation.us-east-1.amazonaws.com:443
at Object._errnoException (util.js:1024:11)
at errnoException (dns.js:55:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
message: 'getaddrinfo EAI_AGAIN cloudformation.us-east-1.amazonaws.com:443',
code: 'NetworkingError',
errno: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: 'cloudformation.us-east-1.amazonaws.com',
host: 'cloudformation.us-east-1.amazonaws.com',
port: 443,
region: 'us-east-1',
retryable: true,
time: 2017-12-23T12:54:27.729Z }
[12:54:27] 'create_cloudformation_stack' errored after 551 ms
[12:54:27] Error: getaddrinfo EAI_AGAIN cloudformation.us-east-1.amazonaws.com:443
at Object._errnoException (util.js:1024:11)
at errnoException (dns.js:55:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)

This is the aws configuration:
AWS Access Key ID [****************GMNA]:
AWS Secret Access Key [****************3tFs]:
Default region name [us-east-1]:
Default output format [None]:

I also checked and my instance is deployed in a public subnet.

Any thoughts on what might be the issue?

Property 'height' does not exist on type 'HTMLElement'

When i try to emulate or build the application, I get the below error.

Error: Error at /Users/user/Desktop/aws-serverless-auth-reference-app/app/.tmp/pages/account/account.ts:47:25
[04:30:24]  Property 'height' does not exist on type 'HTMLElement'. ```

how to secure api?

Hi,
Thanks for your great demo and video, while could I ask a question about how to secure API?
As mentioned, API key is not used to secure API, then how to secure it without details exposed? The details i mean all service we are using from AWS, like I don't want the API consumers know our system is based on AWS API Gateway, so as the API generated SDK, aws, cognito lib, etc.
My case is: i want to develop an API(mainly for server to server) for 3rd developers, i feel AWS API Gateway is great option to control the API calls. but don't know how to protect API,
Thanks very much in advance.

Thanks

Ionic App does not start

Followed all steps. In last step where app has to be started, it fails. Here's content of file: /home/aws-serverless-auth-reference-app/app/npm-debug.log

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/nodejs', '/usr/bin/npm', 'run', 'watch' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prewatch', 'watch', 'postwatch' ]
5 info lifecycle SpaceFinder@~prewatch: SpaceFinder@
6 silly lifecycle SpaceFinder@~prewatch: no script for prewatch, continuing
7 info lifecycle SpaceFinder@~watch: SpaceFinder@
8 verbose lifecycle SpaceFinder@~watch: unsafe-perm in lifecycle true
9 verbose lifecycle SpaceFinder@~watch: PATH: /usr/lib/node_modules/npm/bin/node-gyp-bin:/home/aws-serverless-auth-reference-app/app/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
10 verbose lifecycle SpaceFinder@~watch: CWD: /home/aws-serverless-auth-reference-app/app
11 silly lifecycle SpaceFinder@~watch: Args: [ '-c', 'ionic-app-scripts watch' ]
12 silly lifecycle SpaceFinder@~watch: Returned: code: 137  signal: null
13 info lifecycle SpaceFinder@~watch: Failed to exec watch script
14 verbose stack Error: SpaceFinder@ watch: `ionic-app-scripts watch`
14 verbose stack Exit status 137
14 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/lib/utils/lifecycle.js:255:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:877:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid SpaceFinder@
16 verbose cwd /home/aws-serverless-auth-reference-app/app
17 error Linux 4.4.0-59-generic
18 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "watch"
19 error node v6.9.5
20 error npm  v3.10.10
21 error code ELIFECYCLE
22 error SpaceFinder@ watch: `ionic-app-scripts watch`
22 error Exit status 137
23 error Failed at the SpaceFinder@ watch script 'ionic-app-scripts watch'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the SpaceFinder package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     ionic-app-scripts watch
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs SpaceFinder
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls SpaceFinder
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]

gulp deploy fails on lambda creation - repo needs to be updated for supported nodejs version

[2019-01-16T04:41:55.903Z] INFO: spacefinder/20 on 1f1dc08d454a: Creating Lambd a functions from Swagger API definition...
[2019-01-16T04:41:56.299Z] ERROR: spacefinder/20 on 1f1dc08d454a:
step failed { InvalidParameterValueException: The runtime parameter of nodej s4.3 is no longer supported for creating or updating AWS Lambda functions. We re commend you use the new runtime (nodejs8.10) while creating or updating function s.
at Object.extractError (/home/aws-serverless-auth-reference-app/api/node modules/aws-sdk/lib/protocol/json.js:48:27)
at Request.extractError (/home/aws-serverless-auth-reference-app/api/nod e_modules/aws-sdk/lib/protocol/rest_json.js:45:8)
at Request.callListeners (/home/aws-serverless-auth-reference-app/api/no de_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/home/aws-serverless-auth-reference-app/api/node_module s/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/home/aws-serverless-auth-reference-app/api/node_module s/aws-sdk/lib/request.js:683:14)
at Request.transition (/home/aws-serverless-auth-reference-app/api/node
modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/home/aws-serverless-auth-reference-app/a pi/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /home/aws-serverless-auth-reference-app/api/node_modules/aws-sdk/lib/ state_machine.js:26:10
at Request. (/home/aws-serverless-auth-reference-app/api/node _modules/aws-sdk/lib/request.js:38:9)
at Request. (/home/aws-serverless-auth-reference-app/api/node _modules/aws-sdk/lib/request.js:685:12)
message: 'The runtime parameter of nodejs4.3 is no longer supported for cr eating or updating AWS Lambda functions. We recommend you use the new runtime (n odejs8.10) while creating or updating functions.',
code: 'InvalidParameterValueException',
time: 2019-01-16T04:41:56.299Z,
requestId: '0d7e51cb-1949-11e9-b3cf-f11385aafd34',
statusCode: 400,
retryable: false,
retryDelay: 99.40838729249575 }
[04:41:56] 'create_lambda_functions' errored after 397 ms

question

also looking at using serverless arch for a new app - had also been thinking of dynamodb like you , and since this was a booking app was just curious if the lack of ACID was a problem for you ?

Is the user information in account-management.service.ts secure?

After a user signs in, it seems that everything is just saved to local storage:
https://github.com/awslabs/aws-serverless-auth-reference-app/blob/master/app/src/services/account-management.service.ts#L368

Which looks to be the standard javascript localstorage:
https://github.com/awslabs/aws-serverless-auth-reference-app/blob/master/app/src/services/account-management.service.ts#L560

Is this secure? I was surprised to find these keys and tokens being set to default storage. It seems to defeat the purpose and power of cognito by storing the AWS secret access key here.

From what I can tell, best practice is to use local storage. I guess the big issue is storing that particular key and not just the JWT. If this isn't best practice, can you help point me in the direction of how to use cognito and not compromise the user?

Thanks!

Accessing user claims in lambda with AWS_IAM authorizer.

I am able to successfully use Cognito User pool, federated identities , APIG and Lambda. I am using AWS_IAM authoriser on APIG, I get the IAM policy and accordingly I can execute APIs.

I would like to get user claims like email, name in the lambda function. I did request body template mapping in integration request like below.

"email": "$context.authorizer.claims.email",
"cognitoIdentityPoolId": "$context.identity.cognitoIdentityPoolId",

I can access cognitoIdentityPoolId in lambda as event.cognitoIdentityPoolId but I dont get any value for email. Am I misiing anything? Will I get $context.authorizer.claims.email in case of AWS_IAM authorizer in APIG or using $context.identity.cognitoIdentityPoolId I need to get user claims?

Thanks in advance.

"Bookings" failed on showing booked resource list-Run in a web browser

Hi:
Following developer guide to run the app in web browser through "ionic serve" command.

My environment settings: windows 10, node v6.11.3, npm version 3.10.10, gulp CLI version 1.4.0, ionic CLI 3.9.2, Chrome Version 61.0.3163.100 (Official Build) (64-bit)

After signing in as user1 , selecting a few resources as booked, clicking "Bookings" link in browser, the result was not displayed on panel, though the booking HTTP Get call got the json string of booked resource list for user1

capture1
chrome debug console
capture-console

booking header
capture-header

booking response
capture-response

gulp deploy is stopped with TooManyRequestsException

When running "gulp deploy" to update a created stack,
deployment stops due to a TooManyRequestsException.

e.g.

[2017-01-18T22:30:10.915Z] INFO: spacefinder/7637 on *.local: Created/updated Lambda function spacefinder-api-development-bookings-Delete

    at Request.<anonymous> (/Users/ophilippsen/Sources/awslabs/aws-serverless-auth-reference-app/api/node_modules/aws-sdk/lib/request.js:670:12)
  message: 'Rate exceeded',
  code: 'TooManyRequestsException',
  time: 2017-01-18T22:30:12.274Z,
  requestId: 'ad0a5be0-ddcd-11e6-8677-a198e9e95084',
  statusCode: 429,
  retryable: false,
  retryDelay: 87.86947171700652 }

[23:30:12] 'create_lambda_functions' errored after 2.28 s

As far i understand i ran into throttling - how can i increase allowed requests or overwrite sdk defaults to not run into this problem ?

XMLHttpRequest cannot load error on adding location with UserId

I want to list the locations, according to UserId similar to bookings, I changed the addLocation to this

addLocation(form) {
    this.submitted = true;
    if (form && this.formData.name) {
      let location = {
        name: this.formData.name,
        description: this.formData.description,
        imageUrl: this.formData.imageUrl,
        userId: this.globals.getUserId(),
        userFirstName: this.globals.getUserFirstName(),
        userLastName: this.globals.getUserLastName()
      };
      this.globals.displayLoader("Adding...");
      this.authClient.getClient().locationsCreate(this.globals.getUserId(), location).subscribe(
        (data) => {
          this.globals.dismissLoader();
          this.globals.displayToast(`Location successfully added.`);
          this.navCtrl.pop();
        },
        (err) => {
          this.globals.dismissLoader();
          this.globals.displayAlert('Error encountered',
            `An error occurred when trying to add the location. Please check the console logs for more information.`);
          console.error(err);
        }
      );
    }
  }

and locationsCreate to this

public locationsCreate (userId: string, location: models.Location, extraHttpRequestParams?: any ) : Observable<models.Location> {
        const path = this.basePath + '/locations'
        .replace('{' + 'userId' + '}', String(userId));

        let queryParameters = new URLSearchParams();
        let headerParams = this.defaultHeaders;
        // verify required parameter 'userId' is not null or undefined
        if (userId === null || userId === undefined) {
            throw new Error('Required parameter userId was null or undefined when calling bookingsCreate.');
        }
        // verify required parameter 'location' is not null or undefined
        if (location === null || location === undefined) {
            throw new Error('Required parameter location was null or undefined when calling locationsCreate.');
        }
        let requestOptions: RequestOptionsArgs = {
            method: 'POST',
            headers: headerParams,
            search: queryParameters
        };
        requestOptions.body = JSON.stringify(location);

        return this.http.request(path, requestOptions)
            .map((response: Response) => {
                if (response.status === 204) {
                    return undefined;
                } else {
                    return response.json();
                }
            });
    }

I get the below error if i try to add new locations

XMLHttpRequest cannot load https://cg7fazfa5q.execute-api.us-east-1.amazonaws.com/development/locations. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8101' is therefore not allowed access. The response had HTTP status code 403.

gulp deploy throwing below error.

module.js:472
throw err;
^

Error: Cannot find module '/Users/desktop/aws-serverless-auth-reference-app/api/data'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Function. (/Users/desktop/aws-serverless-auth-reference-app/api/node_modules/rfr/lib/rfr.js:160:12)
at Object. (/Users/desktop/aws-serverless-auth-reference-app/api/lambda/locations.js:3:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)

Unable to Find Public Community AMI - ami-bada16ac

Hopefully, this is the correct place to submit this question. I apologize in advance if it is not. I'm beginning to dive into AWS and Cognito and watched an AWS webcast that references this project. The link is https://www.youtube.com/watch?v=xLvZThZkWjI#t=1149.049 and the title of the webcast is "Add User Sign in and Management to your Apps with Amazon". You are asked to create an EC2 instance as shown below from an excerpt from the quickstart.md file included in this project. I cannot find the referenced Public Community AMI. Does anyone know if another exists that I can use? My experience is primarily Windows but will be working with AWS. The webcast was excellent and I'm excited to move forward with Cognito.

  1. Launch the EC2 instance in your AWS account, using a public community AMI which contains a Docker image with a pre-configured SpaceFinder environment:

    • Public Community AMI: ami-bada16ac
    • Instance type: m4.large

Thanks,
Tom

How can you add a second IdP without losing roles logic?

I'm checking out this reference app in order to start figuring out how to piece together my own application. It's a great start.

If you wanted to allow sign in with Facebook as well, how are you supposed to be able to associate that login with the groups that are being used for role logic in the application?

Am I right to say that this would require rearchitecting so that the groups are stored on the Identity in the Identity Pool?

Otherwise, how does having the ability to federate identities help here if such pertinent logic to the security of the application is strongly tied to a single IdP (i.e. the Cognito User Pool)?

Thanks!

Is userId spoofing prevented?

I was trying to follow the identity flow, but somehow it either disappeared or I lost track.

When booking a location, the userId is sent as part of the body request, as your video shows at
https://youtu.be/n4hsWVXCuVI?list=PLhr1KZpdzukdAg4bXtTfICuFeZFC_H2Xq&t=2191
This looks dangerous, as the user could be able to insert some other userId, not his own.

Apparently, authorizer.js does receive the real userId,
const pId = payload.sub;
does not use this for restricting permissions, but passes it along
policy.principalId = this.principalId;

The booking.js just takes the values as they come and does not check for identity.

function Create(event) {
  let input = JSON.parse(event.body);
  return BookingsTable.put(input);
}

I would assume, if a user managed to insert a wrong userId the data would be entered incorrectly into the database.

Do you agree?
If yes, what would be the best way to prevent it?

How can i get my temporary credentials for my federated Id token ?

Usecase : I want to limit access to my API gateway paths using federated identites.

For that i need to get AWS temporary credentials by using my ID token. I got my Id token but i donot know how to get temporary credentials using Id token.

Here is am passing ID token to cognito credentials map

 var data = {
          UserPoolId: config.cognito.USER_POOL_ID,
          ClientId: config.cognito.APP_CLIENT_ID,
        };
        var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
        var cognitoUser = userPool.getCurrentUser();
        if (cognitoUser != null) {
          cognitoUser.getSession(function(err, result) {
              if (result) {
                  console.log('You are now logged in.');
    
                  // Add the User's Id Token to the Cognito credentials login map.
                  AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                      IdentityPoolId: config.cognito.IDENTITY_POOL_ID,
                      Logins: {
                        'cognito-idp.ap-south-1.amazonaws.com/ap-south-1_G7YbVxxxx': result.getIdToken().getJwtToken()
                      }
                  });
              }
          });
      }

How to get temporary credentials ?

BTW the credentials (ie.access key,secret access key etc) showed in REINVENT is temporary credentials ? If it is then where you had defined them in this app ?

Thanks

Where is Refresh token being managed?

I'm looking at the app, but I can't seem to find where the refresh token is managed.

If I understand correctly, the access token in only good for 1 hour.
So, when calling any AWS service, I think the app should check for token validity and then refresh it before attempting the actual call.

Is there a portion of the code doing this?
I would very much like to see a real example.

Thanks in advance.

CAN'T CONVERT IONIC TO PWA..!!

Hi,
There is manifest and service-worker in the App, though I can't convert this to Progressive Web App.
Data is not saved in cache.so, App didn't work offline.
Can Anyone give the Solution?
Thanks

AWSCognito is not defined in account-management.service.ts

Greetings. Thank you very much for sharing this great project.

Everything worked smoothly out of the box at first, but now I'm having an issue with in account-management.service.ts

I was hoping to understand from someone experienced what is the expected role of declare const AWSCognito: any; and how this object is updated.

My current error is that "AWSCognito is not defined." in the browser's console, and so far I've traced it to : AWSCognito.config.region = CognitoUtil._REGION;

I may have removed the default users that are made in the gulp bootstrap process, though I would expect a different type of error or alert.

Generated Java API SDK has lots of Syntax errors

The following interface is from the generated Java SDK

/**
null
*/
package SpacefinderAPI;

import javax.annotation.Generated;

import com.amazonaws.*;
import com.amazonaws.opensdk.*;
import com.amazonaws.opensdk.model.*;
import com.amazonaws.regions.*;

import SpacefinderAPI.model.*;

/**
 * Interface for accessing SpacefinderAPI.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface SpacefinderAPI {

/**
@param bookings-CreateRequest 
@return Result of the bookings-Create operation returned by the service.
@sample SpacefinderAPI.bookings-Create
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/bookings-Create" target="_top">AWS API Documentation</a>*/
Bookings-CreateResult bookings-Create(Bookings-CreateRequest bookings-CreateRequest);
/**
@param bookings-DeleteRequest 
@return Result of the bookings-Delete operation returned by the service.
@sample SpacefinderAPI.bookings-Delete
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/bookings-Delete" target="_top">AWS API Documentation</a>*/
Bookings-DeleteResult bookings-Delete(Bookings-DeleteRequest bookings-DeleteRequest);
/**
@param bookings-GetRequest 
@return Result of the bookings-Get operation returned by the service.
@sample SpacefinderAPI.bookings-Get
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/bookings-Get" target="_top">AWS API Documentation</a>*/
Bookings-GetResult bookings-Get(Bookings-GetRequest bookings-GetRequest);
/**
@param bookings-ListByResourceIdRequest 
@return Result of the bookings-ListByResourceId operation returned by the service.
@sample SpacefinderAPI.bookings-ListByResourceId
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/bookings-ListByResourceId" target="_top">AWS API Documentation</a>*/
Bookings-ListByResourceIdResult bookings-ListByResourceId(Bookings-ListByResourceIdRequest bookings-ListByResourceIdRequest);
/**
@param bookings-ListByUserIdRequest 
@return Result of the bookings-ListByUserId operation returned by the service.
@sample SpacefinderAPI.bookings-ListByUserId
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/bookings-ListByUserId" target="_top">AWS API Documentation</a>*/
Bookings-ListByUserIdResult bookings-ListByUserId(Bookings-ListByUserIdRequest bookings-ListByUserIdRequest);
/**
@param locations-CreateRequest 
@return Result of the locations-Create operation returned by the service.
@sample SpacefinderAPI.locations-Create
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/locations-Create" target="_top">AWS API Documentation</a>*/
Locations-CreateResult locations-Create(Locations-CreateRequest locations-CreateRequest);
/**
@param locations-DeleteRequest 
@return Result of the locations-Delete operation returned by the service.
@sample SpacefinderAPI.locations-Delete
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/locations-Delete" target="_top">AWS API Documentation</a>*/
Locations-DeleteResult locations-Delete(Locations-DeleteRequest locations-DeleteRequest);
/**
@param locations-GetRequest 
@return Result of the locations-Get operation returned by the service.
@sample SpacefinderAPI.locations-Get
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/locations-Get" target="_top">AWS API Documentation</a>*/
Locations-GetResult locations-Get(Locations-GetRequest locations-GetRequest);
/**
@param locations-ListRequest 
@return Result of the locations-List operation returned by the service.
@sample SpacefinderAPI.locations-List
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/locations-List" target="_top">AWS API Documentation</a>*/
Locations-ListResult locations-List(Locations-ListRequest locations-ListRequest);
/**
@param resources-CreateRequest 
@return Result of the resources-Create operation returned by the service.
@sample SpacefinderAPI.resources-Create
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/resources-Create" target="_top">AWS API Documentation</a>*/
Resources-CreateResult resources-Create(Resources-CreateRequest resources-CreateRequest);
/**
@param resources-DeleteRequest 
@return Result of the resources-Delete operation returned by the service.
@sample SpacefinderAPI.resources-Delete
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/resources-Delete" target="_top">AWS API Documentation</a>*/
Resources-DeleteResult resources-Delete(Resources-DeleteRequest resources-DeleteRequest);
/**
@param resources-GetRequest 
@return Result of the resources-Get operation returned by the service.
@sample SpacefinderAPI.resources-Get
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/resources-Get" target="_top">AWS API Documentation</a>*/
Resources-GetResult resources-Get(Resources-GetRequest resources-GetRequest);
/**
@param resources-ListRequest 
@return Result of the resources-List operation returned by the service.
@sample SpacefinderAPI.resources-List
@see <a href="http://docs.aws.amazon.com/goto/WebAPI/gc4yvjf7uf-1.0.0/resources-List" target="_top">AWS API Documentation</a>*/
Resources-ListResult resources-List(Resources-ListRequest resources-ListRequest);

    /**
    * @return Create new instance of builder with all defaults set.
    */
    public static SpacefinderAPIClientBuilder builder() {
      return new SpacefinderAPIClientBuilder();
    }

    /**
     * Shuts down this client object, releasing any resources that might be held
     * open. This is an optional method, and callers are not expected to call
     * it, but can if they want to explicitly release any open resources. Once a
     * client has been shutdown, it should not be used to make any more
     * requests.
     */
    void shutdown();

}

I download the SDK from here:
screen shot 2018-01-05 at 3 45 31 pm

I am not sure it's specific to this project or a general AWS API gateway bug. If it's specific to this project, please let me how to fix it. Thank you!

Tighten Up Lambda Execution Role Policy By Using Policy Variable (identity ID or Subscriber ID) Fine-Grained Access to DynamoDB

Hi:
In current implementation, the lambda execution role policy is coarse-grained, the lambda execution policy should use cognito variable through policy variable to provide fine-grained access control to Amazon DynamoDB resource- just grant access to items in DynamoDB by identity ID or Subscriber ID.

For Example,
lambda function -spacefinder-api-development-bookings-Delete is attached with an execution role policy as

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"dynamodb:",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "
",
"Effect": "Allow"
}
]
}

This policy is allowing lambda function to perform CRUD operations on any items in any DynamoDB tables.

It might be wise to turn above role execution policy into Fine-Grained access control to grant access to items in spacefinder-api-development-bookings by cognito identity ID. See following new policy.
_{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:BatchGetItem",
"dynamodb:Query",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:BatchWriteItem"
],
"Resource": [
"arn:aws:dynamodb:us-east-1:123456789012:table/spacefinder-api-development-bookings"
],
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["
${cognito-identity.amazonaws.com:sub}"]
}
}
}
]
}_

How to implement booking.js’s Delete function so it can pass cognito identity id to Fine-Grained policy which grants lambda access to items in spacefinder-api-development-bookings table based on cognito identity ID?

Following is current implementation in api/lambda/booking.js
function Delete(event){
return BookingsTable.delete(
event.pathParameters.bookingId
)
}

event contains user1’s cognito identity id ( assuming user spoofing is prevented),

Demo to migrate to AppSync and GraphQL?

I like this project but don't think it would scale well in production. Can you make a branch and/or demo showing how to migrate this project to use AppSync and GraphQL?

Token refresh

Hi

Cognito requires token refresh at least every once per hour. It invalidates token after 1 hour. So my question is this, can this app automatically obtain refreshed token if the last token refresh happened more than say 45 minutes ago? Also since it is an app, if the user puts the app to the background, the refresh will not happen if we are using something like setInterval to get new token. Are these token related issues best solved? Official AWS starter app from Ionic has absolutely no support for token refresh. Great job on this.

Multi tenancy with cognito user pool.

Thanks for very nice reference app. I am planning to use Cognito user pool, federated identities with APIG and lambda.
In my case I am planning to use this for multi-tenant SaaS application. I will have different Cognito user pool per tenant so that I will have flexibility to configure different rules for different tenants . I saw that in config file you have all USER_POOL_ID, CLIENT_ID, IDENTITY_POOL_ID constants which are used in cognito SDK to make calls like authenticate users.

My question is, in my case as I will have different USER_POOL_IDs per tenant how do I handle this in client app? I don't want to update client app as we add new tenants. If I make a API service wrapper for cognito then I need to send password over wire. What is the best practice to handle this use case?

Changing config.js to set region resulted in mixed-region deployment

First off, great job on this guys, a really useful sample.

When I did this last week, I edited the config.js to change AWS_REGION to us-west-2 (the optional step). This resulted in the API Gateway stuff and Cognito user pools deploying to us-west-2, but the lambda functions and Dynamo tables all deployed to us-east-1 (despite my local .aws/config file profile also having us-west-2).

It looks like data.js (in api/lambda/ folder) has the region hard-coded to us-east-1, which makes the Lambda and DynamoDB go there. Should there be a step in the instructions to edit data.js (along with the optional step to change config.js) ?

ionic-app-scripts watch

Hello:

The system that is being used to run the code for the aws-serverless-auth app:
Fedora 24
node v6.9.5
npm v3.10.10

Once ionic serve is executed the process completes to

[17:23:31] build dev finished in 46.37 s

and then fails

[17:23:34] watch failed: A watch configured to watch the following paths failed to start. It likely that a file
referenced does not exist:
/home/aws-user/Documents/aws-serverless-auth-reference-app/app/src//*.(ts|html|s(c|a)ss)
[17:23:34] ionic-app-script task: "watch"
[17:23:34] Error: A watch configured to watch the following paths failed to start. It likely that a file referenced
does not exist: /home/tau/Documents/aws-serverless-auth-reference-app/app/src/
/*.(ts|html|s(c|a)ss)

...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.