airasoul.

Serverless GraphQL authentication with AWS Cognito

Cover Image for Serverless GraphQL authentication with AWS Cognito

The is the second in a two part series of posts where we implement a serverless graphQL service using the Serverless Framework and AppSync, we will in the post secure out GraphQL server with AWS Cognito.

The source code can be found here: discographql, branch two contains the code for this post.

Secure our graphQL server

Continuing from the previous post, in the resources section of our serverless.yml file, add the following very basic Cognito user pool and client.

CognitoUserPool:
  Type: "AWS::Cognito::UserPool"
  Properties:
    UsernameAttributes:
      - "email"
    UserPoolName: discographql-${self:provider.stage}
CognitoUserPoolClient:
  Type: "AWS::Cognito::UserPoolClient"
  Properties:
    ClientName: "web"
    UserPoolId: !Ref CognitoUserPool

In the custom > appsync section of our serverless.yml file remove the current authenticationType and add the following configuration:

authenticationType: AMAZON_COGNITO_USER_POOLS
  userPoolConfig:
    awsRegion: eu-west-2
    defaultAction: ALLOW
    userPoolId:  { Ref: CognitoUserPool }

Lets deploy the server run the following:

npm run deploy

Create user in cogntio

Head over to AWS Cognito and create a new user, with the following configuration:

Create User

Now we have a user, lets head over to AWS Appsync, find your graphQl server and open and press Run a Query

App Sync

If you attempt click the > button the query fails with a 401 error.

Query

Click the link to login with User Pools and select the clientId and login with your new user. You will also be forced to change the password, chich happens after clicking Login

Login

Now when you run a query, it executes successfully, we have successfully setup authentication for our graphQl server.

Query Result