When using AWS Cognito for authentication, you typically don't need a separate DynamoDB table to store user data because Cognito User Pool already provides a managed service for user authentication and user data storage. However, if you need to store additional user-specific data or custom attributes, you might want to use DynamoDB or another database service.
Here's a more detailed breakdown of how you can manage user groups and custom attributes using Cognito and optionally DynamoDB:
1. Cognito User Pool and User Groups
Cognito User Pool allows you to create user groups (also known as user groups or roles) to manage permissions and access control. You can define these groups directly in the Cognito User Pool settings.
2. Custom Attributes
Cognito User Pool supports custom attributes that you can define to store additional user-specific data. These custom attributes can be used to store information that is not part of the standard user attributes provided by Cognito.
3. DynamoDB for Additional Data
If you need to store more complex or relational data associated with users, you can use DynamoDB. For example, you might want to store user preferences, settings, or other metadata that doesn't fit well into the custom attributes of Cognito.
Terraform Code for Cognito and DynamoDB
Here's how you can extend the Terraform code to include Cognito User Pool and DynamoDB:
✅ main.tf
provider "aws" {
region = var.region
}
# S3 Bucket for Hosting React App
resource "aws_s3_bucket" "react_app_bucket" {
bucket = var.bucket_name
acl = "public-read"
website {
index_document = "index.html"
error_document = "index.html"
}
}
# Bucket Policy to allow public read access
resource "aws_s3_bucket_policy" "allow_public_read" {
bucket = aws_s3_bucket.react_app_bucket.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Sid = "PublicReadGetObject"
Effect = "Allow"
Principal = "*"
Action = ["s3:GetObject"]
Resource = "${aws_s3_bucket.react_app_bucket.arn}/*"
}]
})
}
# Upload React Build Files
resource "aws_s3_bucket_object" "react_build_files" {
for_each = fileset("${path.cwd}/../react-app/build/", "**")
key = each.value
source = "${path.cwd}/../react-app/build/${each.value}"
etag = filemd5("${path.cwd}/../react-app/build/${each.value}")
bucket = aws_s3_bucket.react_app_bucket.id
}
# Cognito User Pool
resource "aws_cognito_user_pool" "user_pool" {
name = "my-user-pool"
auto_verified_attributes = ["email"]
schema {
name = "email"
attribute_data_type = "String"
developer_only_attribute = false
mutable = true
required = true
}
schema {
name = "custom:preferences"
attribute_data_type = "String"
developer_only_attribute = true
mutable = true
required = false
}
}
# Cognito User Pool Client
resource "aws_cognito_user_pool_client" "user_pool_client" {
name = "my-user-pool-client"
user_pool_id = aws_cognito_user_pool.user_pool.id
generate_secret = false
}
# DynamoDB Table for Additional User Data
resource "aws_dynamodb_table" "user_data" {
name = "UserData"
billing_mode = "PAY_PER_REQUEST"
hash_key = "username"
attribute {
name = "username"
type = "S"
}
attribute {
name = "preferences"
type = "S"
}
global_secondary_index {
name = "PreferencesIndex"
hash_key = "preferences"
projection_type = "INCLUDE"
non_key_attributes = ["username"]
}
}
✅ variables.tf
variable "region" {
description = "AWS Region"
default = "us-east-1"
}
variable "bucket_name" {
description = "Name of the S3 bucket to host the React app"
type = string
}
✅ outputs.tf
output "website_url" {
value = "http://${aws_s3_bucket.react_app_bucket.website_endpoint}"
}
output "user_pool_id" {
value = aws_cognito_user_pool.user_pool.id
}
output "user_pool_client_id" {
value = aws_cognito_user_pool_client.user_pool_client.id
}
output "dynamodb_table_name" {
value = aws_dynamodb_table.user_data.name
}
Configuring Amplify in React App
Update your src/aws-exports.js to include the Cognito User Pool and Client IDs:
const awsmobile = {
"aws_project_region": "us-east-1",
"aws_cognito_identity_pool_id": "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"aws_cognito_region": "us-east-1",
"aws_user_pools_id": "us-east-1_xxxxxxx",
"aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
"aws_cloud_logic_custom": [
{
"name": "yourAppSyncAPI",
"endpoint": "https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
"region": "us-east-1",
"auth": {
"type": "AMAZON_COGNITO_USER_POOLS",
"jwtToken": {
"authRoleArn": "arn:aws:iam::xxxxxxxxxxxx:role/xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"unauthRoleArn": "arn:aws:iam::xxxxxxxxxxxx:role/xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
}
}
]
};
export default awsmobile;
Using DynamoDB in React App
You can use the AWS SDK to interact with DynamoDB from your React app. Here's an example of how to read and write data to the DynamoDB table:
import AWS from 'aws-sdk/global';
import DynamoDB from 'aws-sdk/clients/dynamodb';
import { Auth } from 'aws-amplify';
const dynamoDB = new DynamoDB.DocumentClient({
region: 'us-east-1',
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
}),
});
const getUserPreferences = async (username) => {
const params = {
TableName: 'UserData',
Key: {
username: username,
},
};
try {
const data = await dynamoDB.get(params).promise();
return data.Item;
} catch (error) {
console.error('Error fetching user preferences:', error);
throw error;
}
};
const saveUserPreferences = async (username, preferences) => {
const params = {
TableName: 'UserData',
Item: {
username: username,
preferences: preferences,
},
};
try {
await dynamoDB.put(params).promise();
} catch (error) {
console.error('Error saving user preferences:', error);
throw error;
}
};
Summary
- Cognito User Pool handles user authentication and basic user data.
- Custom Attributes in Cognito can store additional user-specific data.
- DynamoDB can be used for more complex or relational data associated with users.
- Terraform manages the infrastructure, including S3, Cognito, and DynamoDB.
- Amplify configures the React app to use Cognito and AppSync.
This setup provides a robust solution for managing user authentication, data storage, and access control in a React app deployed to an S3 bucket.