54-61
(54) Section intro
AWS Cognito - user pool vs identity pool
(55) AWS Cognito Identity pools in the console
Authenticated role selection A) use default role
- authenticated
- unauthenticated
B) choose role with rules
- ???
C) choose role from token (-> this app)
- user -> group -> role
(56) Getting AWS temporary credentials // skipped
(57-59) Identity pools in CDK link to userPoolGroup via roleArn
new CfnUserPoolGroup(this.scope, 'admins', {
groupName: 'admins',
userPoolId: this.userPool.userPoolId,
roleArn: this.identityPoolWrapper.adminRole.roleArn,
})
// initialize identityPool
this.identityPool = new CfnIdentityPool(this.scope, 'SpaceFinderIdentityPool', {
allowUnauthenticatedIdentities: true,
cognitoIdentityProviders: [{
clientId: this.userPoolClient.userPoolClientId,
providerName: this.userPool.userPoolProviderName,
}]
});
new CfnOutput(this.scope, 'IdentityPoolId', {
value: this.identityPool.ref
})
// initialize roles
this.authenticatedRole = this.createRole('CognitoDefaultAuthenticatedRole', true)
this.unauthenticatedRole = this.createRole('CognitoDefaultUnauthenticatedRole', false)
this.adminRole = this.createRole('CognitoAdminRole', true)
this.adminRole.addToPolicy(new PolicyStatement({
effect: Effect.ALLOW,
actions: ['s3:ListAllMyBuckets'],
resources: ['*']
}))
private createRole(id: string, authenticated: boolean) {
return new Role(this.scope, id, {
assumedBy: new FederatedPrincipal('cognito-identity.amazonaws.com', {
StringEquals: {
'cognito-identity.amazonaws.com:aud': this.identityPool.ref
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': authenticated ? 'authenticated' : 'unauthenticated'
},
},
'sts:AssumeRoleWithWebIdentity'
)
});
}
// attach roles
new CfnIdentityPoolRoleAttachment(this.scope, 'RolesAttachment', {
identityPoolId: this.identityPool.ref,
roles: {
'authenticated': this.authenticatedRole.roleArn,
'unauthenticated': this.unauthenticatedRole.roleArn,
},
roleMappings: {
adminsMapping: {
type: 'Token',
ambiguousRoleResolution: 'AuthenticatedRole',
identityProvider: `${this.userPool.userPoolProviderName}:${this.userPoolClient.userPoolClientId}`
}
}
})
(60) testing whether it works command line to add / remove user from group
op run -- bash -c 'aws cognito-idp admin-remove-user-from-group --user-pool-id ${USER_POOL_ID} --username ${TEST_USER_NAME} --group-name admins'
op run -- bash -c 'aws cognito-idp admin-add-user-to-group --user-pool-id ${USER_POOL_ID} --username ${TEST_USER_NAME} --group-name admins'
(61) Further reading Fine-grained Access Control with Amazon Cognito Identity Pools - YouTube AWS re:Invent 2018: Deconstructing SaaS: Building Multi-Tenant Solutions on AWS (ARC418-R1) - YouTube AWS re:Invent 2017: [REPEAT] Serverless Authentication and Authorization: Identity M (SRV403-R) - YouTube