Using Angular to Invoke APIs Hosted on Amazon API Gateway, Secured using Cognito User Pools

This article describes how to secure an API in Amazon API Gateway. Here we’ll see how to invoke a secure API programmatically from Angular.

Hitting an insecure endpoint is pretty straightforward. In app.module.ts:

import { HttpClientModule } from '@angular/common/http';

And add HttpClientModule after BrowserModule in NgModule.imports. In app.component.ts:

import { HttpClient } from '@angular/common/http';

And inject HttpClient in the constructor:

constructor(private httpClient: HttpClient) {}

Call the API anywhere:

this.httpClient.get(<api-endpoint>).subscribe();

Once the API is secured, this won’t work anymore. Let’s see how to get it working again. First, get the access token:

this.httpClient.post('https://<domain-prefix>.auth.ap-south-1.amazoncognito.com/oauth2/token?grant_type=client_credentials', {}, {
     headers: new HttpHeaders({
         Authorization: 'Basic ' + btoa('<client-id>:<secret>'),
         'Content-Type': 'application/x-www-form-urlencoded'
     })
}).subscribe();

You’ll find the domain prefix, client ID & secret in the user pool settings:

Now use the access token to hit the secured endpoint:

this.httpClient.get('<api-endpoint>', {
    headers: new HttpHeaders({
        Authorization: 'Bearer ' + '<access-token>'
    })
}).subscribe();

This should get us the expected response.

 

Harish KM is a Cloud Evangelist and a Full Stack Engineer at QloudX. Harish is very passionate about cloud native solutions and using the best tools for projects. This means that he is an expert in a multitude of application languages and is up to date with all the new offerings and services from cloud providers, especially AWS.

2 Replies to “Using Angular to Invoke APIs Hosted on Amazon API Gateway, Secured using Cognito User Pools”

  1. David says:

    Simple and fixed the issue I was dealing with. Thanks for making such a simple to follow help article.

  2. Juan Jose says:

    nice Work! it help me =)

Leave a Reply

Your email address will not be published. Required fields are marked *