Files
remote-sensing/COGNITO_GUIDE.md
T

6.7 KiB

Cognito Authentication Guide

Hướng Dẫn Xác Thực Cognito

Kết quả Test

Authentication Flow thành công:

Cognito Tokens → AWS Credentials → S3 Access
     ✓               ✓                  ✓

Thông tin User từ Cognito:

  • Username: hienm2523001
  • Name: Hien Phan
  • Email: hienm2523001@gstudent.ctu.edu.vn
  • Groups:
    • default-group
    • allocation:R-19244:CSIRO and Vietnam partners
  • Token Expiry: ~8 giờ từ khi login

S3 Buckets có thể truy cập:

sentinel-cogs (us-west-2)
sentinel-s2-l2a (eu-central-1)


📁 Files đã tạo

1. cognito_auth.py

Module Python để xác thực với Cognito tokens

Tính năng:

  • Load Cognito tokens từ file
  • Decode và hiển thị thông tin user
  • Load AWS credentials (đã được EASI exchange từ Cognito)
  • Set credentials vào environment
  • Test S3 access

2. test_cognito_s3.py

Script test đầy đủ flow: Cognito → AWS → S3


🚀 Cách sử dụng

Quick Test

python test_cognito_s3.py

Sử dụng trong code

1. Load Cognito authentication:

from cognito_auth import CognitoAuthenticator

# Initialize
auth = CognitoAuthenticator(region='ap-southeast-1')

# Load tokens và credentials
auth.load_tokens_from_file('train_files/crediential.txt')

# Xem thông tin user
auth.print_token_info()

# Get AWS credentials
auth.get_credentials_from_cognito()

# Set vào environment
auth.set_environment_credentials()

2. Truy cập S3:

# Test S3 access
auth.test_s3_access('sentinel-cogs', 'us-west-2')

3. Sử dụng với datacube:

from datacube.utils.rio import configure_s3_access

# Configure S3 access
configure_s3_access(
    aws_unsigned=False,
    region_name='us-west-2',
    cloud_defaults=True
)

# Load dữ liệu như bình thường

🔄 Cấu trúc File Credentials

File train_files/crediential.txt chứa:

# AWS Credentials (đã được exchange từ Cognito bởi EASI)
export AWS_ACCESS_KEY_ID="ASIA..."
export AWS_SECRET_ACCESS_KEY="..."
export AWS_SESSION_TOKEN="..."

# Cognito Tokens
Cognito: eyJraWQi...  # Access Token
ID: eyJraWQi...        # ID Token

📊 So sánh 2 phương pháp

Feature Direct Credentials Cognito Tokens
Authentication Không có User info, groups
S3 Access
User Identity Chỉ có role ARN Username, email, groups
Token Info Không Expiry time, claims
Security Basic Better (identity-based)

💡 Flow hoạt động

Trong hệ thống EASI:

1. User login vào EASI Hub
   ↓
2. AWS Cognito xác thực
   ↓
3. Cognito trả về:
   - Access Token (authentication)
   - ID Token (user info)
   ↓
4. EASI Backend exchange tokens → AWS Credentials
   ↓
5. User nhận cả Cognito tokens + AWS credentials
   ↓
6. Sử dụng credentials để truy cập S3

Trong code của bạn:

# Load từ file
auth.load_tokens_from_file()
  
# Parse user info
auth.print_token_info()
  
# Get AWS credentials (đã có sẵn trong file)
auth.get_credentials_from_cognito()
  
# Set environment
auth.set_environment_credentials()
  
# Access S3
auth.test_s3_access()

⚙️ Advanced Usage

Decode token để lấy thông tin:

import jwt

decoded = jwt.decode(id_token, options={"verify_signature": False})
print(decoded)
# {
#   'cognito:username': 'hienm2523001',
#   'email': 'hienm2523001@gstudent.ctu.edu.vn',
#   'cognito:groups': ['default-group', 'allocation:R-19244:...'],
#   'exp': 1772661158,
#   ...
# }

Check token expiration:

from datetime import datetime

exp = decoded['exp']
exp_time = datetime.fromtimestamp(exp)
now = datetime.now()

if exp_time > now:
    print(f"Token còn hiệu lực đến: {exp_time}")
else:
    print("Token đã hết hạn!")

Sử dụng với boto3:

import boto3

s3 = boto3.client(
    's3',
    aws_access_key_id=auth.aws_credentials['AccessKeyId'],
    aws_secret_access_key=auth.aws_credentials['SecretAccessKey'],
    aws_session_token=auth.aws_credentials['SessionToken']
)

# List objects
response = s3.list_objects_v2(Bucket='sentinel-cogs', MaxKeys=10)

🔒 Security Notes

Best Practices:

  • Token có thời hạn (tự động expire sau ~8 giờ)
  • Sử dụng HTTPS cho mọi API calls
  • KHÔNG commit tokens vào Git
  • KHÔNG share tokens công khai
  • Refresh tokens khi hết hạn

⚠️ Lưu ý:

  • Cognito tokens và AWS credentials ĐỀU CÓ THỜI HẠN
  • Khi hết hạn, cần login lại vào EASI hub
  • File .gitignore nên bao gồm train_files/crediential.txt

🐛 Troubleshooting

Error: "Token đã hết hạn"

✗ Token EXPIRED at: 2026-03-05 04:52:38

Giải pháp: Login lại vào EASI hub để lấy tokens mới

Error: "ModuleNotFoundError: No module named 'jwt'"

pip install PyJWT

Error: "No AWS credentials available"

Giải pháp:

  • Check file train_files/crediential.txt có đầy đủ không
  • Đảm bảo có cả AWS credentials VÀ Cognito tokens

Error: "AccessDenied" khi truy cập S3

Giải pháp:

  • Token có thể đã hết hạn
  • Bucket có thể yêu cầu quyền cao hơn
  • Thử bucket khác (public bucket)

📚 Dependencies

pip install boto3 botocore PyJWT datacube rasterio

Hoặc:

pip install -r requirements_api.txt

📞 Contact

  • EASI Asia Support: CSIRO EASI Hub
  • Project: R-19244: CSIRO and Vietnam partners
  • Region: ap-southeast-1

📝 Example Output

======================================================================
Test S3 Access Using Cognito Tokens
======================================================================

[1/5] Loading Cognito tokens from file...
✓ AWS credentials loaded from file
✓ Cognito tokens loaded successfully

[2/5] Displaying token information...
User Information:
  Username: hienm2523001
  Name: Hien Phan
  Email: hienm2523001@gstudent.ctu.edu.vn
  Groups: default-group, allocation:R-19244:CSIRO and Vietnam partners
  Token expires: 2026-03-05 04:52:38
  Time remaining: 7h 45m

[3/5] Getting AWS credentials...
✓ Using AWS credentials loaded from file

[4/5] Configuring environment...
✓ AWS credentials set in environment

[5/5] Configuring datacube S3 access...
✓ Datacube S3 access configured

S3 Access Results:
  ✓ sentinel-cogs
  ✓ sentinel-s2-l2a

✓ SUCCESS: Cognito authentication working!
======================================================================

Last updated: March 4, 2026
Status: Working perfectly!