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.

6 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 =)

  3. Vik says:

    Is this secure to have client-id and secret in angular code?
    Authorization: ‘Basic ‘ + btoa(‘:’),

    • Harish KM says:

      Nice catch Vik. You’re right. Putting the secret in Angular code isn’t very secure. I’ll update the post when I get a chance. Thanks! 🙂

      • vinayak says:

        How can we use Hosted UI for authentication in angular with secret key

        • Harish KM says:

          Using the secret key won’t be the right way to go if you need Cognito’s hosted UI. Instead, create a public app client in your Cognito user pool as described here. Then you would use its client ID in your angular code when you redirect your users to the Cognito hosted UI for login.

Leave a Reply

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