DEV Community

Cover image for AWS Cognito and AWS API Gateway
Paul Allies
Paul Allies

Posted on

AWS Cognito and AWS API Gateway

Let's configure AWS cognito to secure our AWS API Gateway.

Open AWS Cognito:

Screenshot 2021-08-08 at 20.58.47

Create a default User Pool

Screenshot 2021-08-08 at 20.59.55

After the pool is created, go back into the setup and create an app client

Screenshot 2021-08-08 at 21.05.32

Update the App Client Settings

Screenshot 2021-08-08 at 21.14.24

Add a domain to host your auth pages

Screenshot 2021-08-08 at 21.17.32

Go back into "App client settings" and "Launch Hosted UI".

Screenshot 2021-08-08 at 21.23.15

Now to secure your API, within your AWS API Gateway configuration, create a Cognito Authorizer

Screenshot 2021-08-08 at 21.31.15

Now secure an API endpoint by updating the "Method Request" of that method, You might need to refresh your browser to update list of authorizers.

Screenshot 2021-08-08 at 22.15.55

Re-deploy the API and test the endpoint. You now get the following response

{"message":"Unauthorized"}
Enter fullscreen mode Exit fullscreen mode

Let's get a token. Go back to the Cognito HostedUI SignIn page and request a token by changing the "code" query string param to "token" because we'd like the Cognito service to return a token on successful login.

https://app2.auth.eu-west-1.amazoncognito.com/login?client_id=xxxxxxxxxxxx&response_type=token.....
Enter fullscreen mode Exit fullscreen mode

on successful sign-in an id_token and access_token will be returned in the url. Retrieve the access_token.

To now access the secure endpoint, we now need provide an access token in the "Authorization" header

GET https://xxxxxxxx.execute-api.af-south-1.amazonaws.com/dev
Authorization: vLnNpZ25pbi51c2Vy...

Enter fullscreen mode Exit fullscreen mode

We now get the response:

{"message":"Welcome to My Secure API"}
Enter fullscreen mode Exit fullscreen mode

Done!

Top comments (0)