AWS & Typescript Masterclass - Securing APIs with AWS Cognito

September 14th, 2022

44-53

 


 

(44) Section intro

  • cognito

  • user pools

  • JWT tokens

  • groups

 


 

(45) AWS Cognito

AWS Cognito - user pool vs identity pool

 


 

(46) Cognito in AWS console

  1. create user pool

  2. create app integration

  3. create app client

 

command line force set password for user for dev

aws cognito-idp admin-set-user-password --user-pool-id ${USER_POOL_ID} --username ${TEST_USER_NAME} --password "${TEST_USER_PASSWORD}" --permanent

 

or with 1password cli

op run -- bash -c 'aws cognito-idp admin-set-user-password --user-pool-id ${USER_POOL_ID} --username ${TEST_USER_NAME} --password "${TEST_USER_PASSWORD}" --permanent'

 

(47) Generating JWT tokens with AWS Amplify

(for dev within the playground)

npm i aws-amplify @aws-amplify/auth

 


(48) Using AWS Cognito Tokens

current: identity token

future: more fine grained access control

 


 

(49) Understanding JWT tokens

https://jwt.io/

 

cognito groups

  • name

  • IAM role

assign user to group

-> JWT payload will contain

"group": "<group-name>"

 


 

(50-52) Cognito with CDK

// UserPool

this.userPool = new UserPool(this.scope, 'SpaceUserPool', {

userPoolName: 'SpaceUserPool',

selfSignUpEnabled: true,

signInAliases: {

username: true,

email: true

}

})

new CfnOutput(this.scope, 'UserPoolId', {

value: this.userPool.userPoolId

})

 

 

// UserPoolClient

this.userPoolClient = this.userPool.addClient('SpaceUserPool-client', {

userPoolClientName: 'SpaceUserPool-client',

authFlows: {

adminUserPassword: true,

custom: true,

userPassword: true,

userSrp: true,

},

generateSecret: false,

})

new CfnOutput(this.scope, 'UserPoolClientId', {

value: this.userPoolClient.userPoolClientId

})

 

 

// Authorizer

this.authorizer = new CognitoUserPoolsAuthorizer(this.scope, 'SpaceUserAuthorizer', {

cognitoUserPools: [this.userPool],

authorizerName: 'SpaceUserAuthorizer',

identitySource: 'method.request.header.Authorization',

})

this.authorizer._attachToApi(this.api)

 

// use in api

const optionsWithAuthorizer: MethodOptions = {

authorizationType: AuthorizationType.COGNITO,

authorizer: {

authorizerId: this.authorizer.authorizer.authorizerId

}

}

const helloLambdaIntegration = new LambdaIntegration(helloLambdaNodeJs);

const helloLambdaResource = this.api.root.addResource('hello');

helloLambdaResource.addMethod('GET', helloLambdaIntegration, optionsWithAuthorizer);

 


 

(53) Access control with Cognito Groups

fine grained access control

new CfnUserPoolGroup(this.scope, 'admins', {

groupName: 'admins',

userPoolId: this.userPool.userPoolId,

// roleArn: ,

})

 

function isAuthorized(event: APIGatewayProxyEvent) {

const groups = event.requestContext.authorizer?.claims['cognito:groups']

if (groups) {

return (groups as string).includes('admins')

} else return false

}