
Securing an AppSync Events Serverless Chat App with Amazon Cognito
This article demonstrates how to add authentication and authorization to a chat application, ensuring only authorized users are able to publish to channels they are members of. Cognito handles the login, with a set of several pre-seeded users to demonstrate the group chat functionality. Both the CDK project and the front-end code are included, easy to deploy and test on your own AWS account for hands-on learning.
I often feel like Cognito is such an underrated service, but I am a big user for a long time, both for personal and professional projects. In this article, I will demonstrate how to use it to add authentication and authorization to a chat application, securing both REST API endpoints, as well as AppSync Events API WebSocket endpoint.
Here's a brief summary of what's included:
- TypeScript CDK project ready to deploy the full backend to your own AWS account
- Ready-made front-end chat application which connects to the deployed backend
- Features like listing available channels, fetching channel message history, authorization per channel
...and more! So, make sure to stick to the end, and try to run it yourself for a true hands-on learning experience.
What we're building
The focus of the article won't be on how to build chat, nor deep dive on Amazon Cognito as a whole, but rather on a niche part of integrating authorization in a real-time system like this. Such focus gives the opportunity to learn the specifics instead of going wide on general topics. What we have here is a basic group chat web application with several pre-defined channels, and pre-seeded users, who are members of different channels. Setup like that will enable us to test specific scenarios when authorization is in question.
Architecture
The chat architecture consists of AppSync Events API for real-time communication, and an API Gateway REST API for fetching channels and message history per channel, powered by the respective Lambda functions and DynamoDB tables. Both APIs are protected with the Amazon Cognito User Pool.

Both tables are using the channel as the partition key, and we have a global secondary index on the memberships table so we can fetch channels for a user.
Signing in with Cognito
User pool and managed login
As mentioned, there are seeded users in the User Pool, so there is no self sign-up. This is done for simplicity of the article, and it keeps the focus on the points I want to illustrate. For the same reason, we will use the managed login. The pool gets a Cognito domain for managed login, and a public app client with no secret:
const userPool = new UserPool(this, 'ChatUserPool', { selfSignUpEnabled: false, signInAliases: {username: true}, standardAttributes: {fullname: {required: false, mutable: true}},});const domain = userPool.addDomain('ChatUserPoolDomain', { cognitoDomain: {domainPrefix: `serverless-chat-${this.account}`}, managedLoginVersion: ManagedLoginVersion.NEWER_MANAGED_LOGIN,});const userPoolClient = userPool.addClient('ChatWebClient', { generateSecret: false, authFlows: {adminUserPassword: true}, oAuth: { flows: {authorizationCodeGrant: true}, scopes: [OAuthScope.OPENID, OAuthScope.PROFILE], callbackUrls: ['http://localhost:5173/'], logoutUrls: ['http://localhost:5173/'], },});Managed login uses a branding style per app client, so we assign Cognito's default style like the following:
new CfnManagedLoginBranding(this, 'ChatManagedLoginBranding', { userPoolId: userPool.userPoolId, clientId: userPoolClient.userPoolClientId, useCognitoProvidedValues: true,});Cognito only redirects back to
https:// URLs, or http://localhost for development, so for that reason we make the client served on http://localhost:5173 instead of opened from disk as a plain HTML file, which worked in my previous articles.Sign-in with Amplify Auth: authorization code and PKCE
Managed login uses the authorization code grant with PKCE. This is the current standard when security is in question, and Amplify Auth runs the whole flow for us. Since we have a very plain front-end client, we use a small shortcut / workaround to load Amplify from esm.sh as ES modules, for simplicity:
import { Amplify } from 'https://esm.sh/aws-amplify@6.22.2?deps=@aws-amplify/core@6.19.3';import { fetchAuthSession, signInWithRedirect, signOut } from 'https://esm.sh/aws-amplify@6.22.2/auth?deps=@aws-amplify/core@6.19.3';import 'https://esm.sh/aws-amplify@6.22.2/auth/enable-oauth-listener?deps=@aws-amplify/core@6.19.3';
Amplify.configure({ Auth: { Cognito: { userPoolId: cfg.userPoolId, userPoolClientId: cfg.clientId, loginWith: { oauth: { domain: new URL(cfg.cognitoDomain).host, scopes: ['openid', 'profile'], redirectSignIn: [cfg.redirectUri], redirectSignOut: [cfg.redirectUri], responseType: 'code', }, }, }, },});signInWithRedirect() sends the user to managed login. Back on the page, the listener
exchanges the code for tokens, and fetchAuthSession() returns them. It refreshes them once
they expire:export async function getIdToken() { const { tokens } = await fetchAuthSession(); return tokens?.idToken ?? null;}Amplify is a very useful library that offers a lot, so it's good to note that we use its Auth part only, again, for simplicity.
Cognito auth on AppSync Events and on API Gateway
An Event API supports API keys, Lambda authorizers, IAM, OpenID Connect and Cognito user pools. In my previous articles I used a plain API key, which is not enough to identify users. It was a workaround used for simplicity, and to quickly demonstrate different aspects rather than authentication. This time, we rely on Cognito, and now every request contains a verified identity, so the handlers get it via the token claims.
Appsync Events API: connect, publish and subscribe
Connect, publish and subscribe can each have their own auth modes. Here all three use the
user pool:
const eventApi = new EventApi(this, 'ChatAppSyncEventsApi', { apiName: 'ChatAppSyncEventApiCognito', authorizationConfig: { authProviders: [{ authorizationType: AppSyncAuthorizationType.USER_POOL, cognitoConfig: {userPool}, }], connectionAuthModeTypes: [AppSyncAuthorizationType.USER_POOL], defaultPublishAuthModeTypes: [AppSyncAuthorizationType.USER_POOL], defaultSubscribeAuthModeTypes: [AppSyncAuthorizationType.USER_POOL], },});Over the WebSocket, to connect, the token is base64url-encoded in a
subprotocol, together with the API's HTTP host. Then each
subscribe and publish message carries the same object in authorization . The HTTP publish endpoint ( POST https://<http-host>/event ) takes the token in the Authorization header.The REST API: Cognito authorizer
Regarding our REST API endpoints, a
CognitoUserPoolsAuthorizer is the default:const authorizer = new CognitoUserPoolsAuthorizer(this, 'ChatApiAuthorizer', { cognitoUserPools: [userPool],});const api = new RestApi(this, 'ServerlessChatApi', { defaultCorsPreflightOptions: { allowOrigins: ['http://localhost:5173'], allowMethods: ['GET'], allowHeaders: ['Authorization', 'Content-Type'], }, defaultMethodOptions: {authorizer, authorizationType: AuthorizationType.COGNITO},});Authorization
As we all (hopefully) know, authentication proves who you are, while authorization checks what you can do. In this case, it still has to check that you're a member of the channel. For the REST API these checks are in the Lambda functions (i.e. return only channels that the user is a member of), while for AppSync Events API the checks are built in
onSubscribe and onPublish handlers. Both handlers use a DynamoDB data source on the memberships table.Subscribe
The
onSubscribe handler checks if the user whose token is passed actually belongs to the channel they are trying to subscribe to, and it does so by reading the memberships table from its data source. One caveat here is that AppSync Events API accepts wildcards, so we implement a small piece of app specific code to accept only channels specific to our app, for example:// Channels look like /serverlesschat/channels/<name>function channelName(ctx) { const segments = ctx.info.channel.segments if (segments.length !== 3 || segments[1] !== 'channels' || segments[2] === '*') { return null } return segments[2]}If any of the conditions described is not met, the handler should return an unauthorized result.
Publish
Membership check is performed in the
onPublish handler, via its data source. A DynamoDB transaction does both: a condition check on the membership item, plus one put per message.return ddb.transactWrite({ items: [ { conditionCheck: { table: MEMBERSHIPS_TABLE, key: { channel, userId: sub }, condition: { userId: { attributeExists: true } }, }, }, ...messages.map(({ item }) => ({ putItem: { table: MESSAGES_TABLE, key: { channel: item.channel, id: item.id }, item, }, })), ],})If the user isn't authorized to send the message in the channel, the check fails and DynamoDB cancels the whole transaction, so nothing is written. A proper use-case for the transactions.
Message history and the channel list
The two Lambda functions read the caller from the authorizer's claims and check the memberships table themselves:
export function callerId(event: APIGatewayProxyEvent): string { return event.requestContext.authorizer?.claims?.sub;}
export async function isMember(channel: string, userId: string): Promise<boolean> { const result = await ddb.send(new GetCommand({ TableName: process.env.MEMBERSHIPS_TABLE, Key: {channel, userId}, })); return result.Item !== undefined;}// GET /channels/{channel}/messagesconst channel = event.pathParameters?.channel;if (!channel || !(await isMember(channel, callerId(event)))) { return json(403, {message: 'Forbidden'});}GET /channels queries the memberships table's global secondary index, so it only returns pre-filtered list of channels a calling user is a member of:const memberships = await ddb.send(new QueryCommand({ TableName: process.env.MEMBERSHIPS_TABLE, IndexName: 'byUser', KeyConditionExpression: 'userId = :userId', ExpressionAttributeValues: {':userId': callerId(event)},}));Running the demo
Okay, finally we are coming to the interesting stuff!
You need Node.js 24 or later, the AWS CLI v2 with credentials for the account and region to
deploy to, and curl.
Deploy
Clone the project:
git clone https://github.com/imflamboyant/serverless-aws-chat-appsync-events-cognito.gitThen, in the project directory run install and deploy (you need to have already boostrapped your account and region for CDK):
npm installnpm run deployThe deploy prints the stack outputs. Export the ones the next steps use:
export USER_POOL_ID=<UserPoolId>export CLIENT_ID=<UserPoolClientId>export REST_API=<RestApiUrl>export EVENTS_HTTP=<EventApiHttpDns>export EVENTS_REALTIME=<EventApiRealtimeDns>Seeding users
Three users, with
scripts/create-user.sh , where Carol isn't a
member of #engineering channel:./scripts/create-user.sh alice '<password>' general random engineering./scripts/create-user.sh bob '<password>' general random engineering./scripts/create-user.sh carol '<password>' general randomPick any password with at least 8 characters, upper and lower case letters, a number and a
symbol. Leave out single quotes and commas.
Run the client
Copy
client/config.example.js to client/config.js and fill in the deploy outputs. Then:npm run clientOpen http://localhost:5173/ and sign in as Alice. In a second browser, or a second browser or an incognito window, and sign in as Carol. She sees #general and #random, but not #engineering. You can experiment with a third browser and user, and try to send messages to channels and see how the app behaves.
Conclusions and cleanup
In this article we covered a very important topic, which is never simple, especially in real-time apps. We demonstrated how to build authentication and authorization on a real-time chat application, diving deep into the details around the authorization logic. Focus is kept on the essence, keeping the article pragmatic, thus providing the front-end client code out of the box. With clear deployment and testing steps, it makes it effortless to try out the example yourself, making it a truly hands-on experience. When you are done, cleanup is one command in the terminal:
npn run destroyThe user pool, both tables and the Lambdas' log groups are set to be deleted with the stack,
so this removes everything, users and messages included. I hope you enjoyed, and for any questions feel free to reach out in the comments section!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article