In this post, I will explain how to securely connect your Angular application to the API and AWS resources. API is secured using AWS Cognito and we are going to access AWS Resources with the help of Cognito.
The Design
- Access Your Server-side Resources with a User Pool (Access your secure API build with Java and Spring Boot)
- Access AWS Services with a User Pool and an Identity Pool (Access your records in AWS DynamoDB )
Angular, Cognito and Java API integration |
Setting up the Angular Application
Create an Angular Application using Angular CLI(ng new my-first-project) then add AWS Amplify to it (npm install aws-amplify @aws-amplify/ui-angular).
Next, configure the project by creating a file with the name aws-exports.js in the angular_app_root/src/app folder. The location of this file can be changed, this is the location I used for my project.
aws-exports.js contains all the details needed to connect with AWS Cognito.
const awsmobile = {
"aws_project_region": "ap-southeast-1",
"Auth": {
"identityPoolId": "ap-southeast-1:xxxxxxxxxxxxxxxx",
"region": "ap-southeast-1",
"userPoolId": "ap-southeast-xxxxxxxxxxx",
"userPoolWebClientId": "xxxxxxxxxxxxxxxxxxxxxx"
}
};
export default awsmobile;
Finally, update app.module.ts and app.component.html to finalize the Cognito integration. I also linked Bootstrap to make things look nicer.
Add AWS SDK
Once the integration is done, you will be able to communicate with AWS Resources using the Angular Application.
For this integration to be successful, the AWS identity pool authenticated role needs to have the relevant permissions attached to it. I'll explain this in the next section.
Configuring AWS Cognito
Access Your Server-side Resources with a User Pool |
Access AWS services with a User Pool and an Identity Pool |
Getting credentials from Cognito example code:
Policy to access DynamoDB |
Securing the API
In order to implement a secure API, you have to implement a resource server. Spring boot enables you to easily implement this feature with the help of a few annotations and configurations.
In one of my earlier posts, I have described this in much more details. Please check it.
Source codes
I have uploaded the Angular and Spring Boot projects to Github.
DEMO
Secure APIs and Access AWS Resources with Angular and Cognito |
References
- https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/
- https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html
- https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-scenarios.html#scenario-aws-and-user-pool
- https://cli.angular.io/
- https://angular.io/docs
- https://docs.amplify.aws/start/q/integration/angular
Comments
Post a Comment