Alexander Zeitler

Alexander Zeitler

Creating an AWS Cognito user pool with OAuth flows using AWS CDK

Published on Sunday, October 4, 2020

I tried to setup an AWS Cognito user pool supporting OAuth 2.0 client credential flow using AWS CDK.

As of version 1.66.0. CDK allows you to create a Cognito User Pool very straight forward:

mkdir idp-stack && cd idp-stack
cdk init idp-stack --language typescript
npm install @aws-cdk/aws-cognito
import { OAuthScope, UserPool } from "@aws-cdk/aws-cognito";

const pool = new UserPool(this, "dev-userpool", {
userPoolName: "dev-userpool",
});

Next you would assume, you can add a client with client credential flow enabled (as explained in the links above). So here it is:

pool.addClient("console-client", {
generateSecret: true,
oAuth: {
flows: {
clientCredentials: true,
},
scopes: [OAuthScope.custom("https://resource-server//get-todos")],
},
});

In order to be able to add a custom scope like https://resource-server//get-todos, first you need to create a resource server. But it is not connected to the user pool in terms of a function to call on the pool instance (which makes sense if you think about it for a while).

So here we go:

new CfnUserPoolResourceServer(this, "dev-userpool-resource-server", {
identifier: "https://resource-server/",
name: "dev-userpool-resource-server",
userPoolId: pool.userPoolId,
scopes: [
{
scopeDescription: "Get todo items",
scopeName: "get-todos",
},
],
});

Now we can use the get-todos scope in our client (take care of the correct convention to specify the scope here):

pool.addClient("console-client", {
generateSecret: true,
oAuth: {
flows: {
clientCredentials: true,
},
scopes: [OAuthScope.custom("https://resource-server//get-todos")],
},
});

Make sure to take care of the convention for scopes: <resourceserver-identifier>//<scope-name> (notice the double slash).

Additionally we'll specify a domain for our user pool:

pool.addDomain("CognitoDomain", {
cognitoDomain: {
domainPrefix: "dev-userpool",
},
});

Lets try cdk deploy and everything should be fine:

npm run build && npm run cdk deploy

This is the result - and we're done ✅


The stack IdpStack already includes a CDKMetadata resource
IdpStack: deploying...
IdpStack: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (6/6)

✅ IdpStack

The user pool:

The client:

The resource server:

The full code example can be found here.

What are your thoughts about "Creating an AWS Cognito user pool with OAuth flows using AWS CDK"?
Drop me a line - I'm looking forward to your feedback!
Imprint | Privacy