Skip to content

Latest commit

 

History

History
273 lines (219 loc) · 7.61 KB

File metadata and controls

273 lines (219 loc) · 7.61 KB

Testing Guide - User Service with Cognito

Your Cognito Configuration

Based on your sign-in request, here are your Cognito details:

  • Region: ap-southeast-1
  • Client ID: 1d1jkchdvgt5tldbb0hivruird
  • User Pool ID: ⚠️ Still needed - see instructions below

Step 1: Find Your User Pool ID

The User Pool ID is different from the Client ID. Here's how to find it:

Method 1: AWS Console

  1. Go to AWS Console
  2. Navigate to Amazon Cognito
  3. Select User Pools from the left sidebar
  4. Click on your user pool name
  5. The Pool ID is displayed at the top
    • Format: ap-southeast-1_XXXXXXXXX (9 random characters after underscore)

Method 2: AWS CLI

aws cognito-idp list-user-pools --max-results 10 --region ap-southeast-1

Look for the pool with your client ID and note its Id field.

Method 3: Check Cognito Response

When you sign in, Cognito returns tokens. You can decode the access token (without verification) to see the issuer:

# The issuer contains the User Pool ID
# Format: https://cognito-idp.ap-southeast-1.amazonaws.com/ap-southeast-1_XXXXXXXXX

Step 2: Get Tokens from Cognito

Use your existing sign-in request to get tokens:

curl -X POST 'https://cognito-idp.ap-southeast-1.amazonaws.com/' \
  --header 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
  --header 'Content-Type: application/x-amz-json-1.1' \
  --data '{
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "1d1jkchdvgt5tldbb0hivruird",
    "AuthParameters": {
      "USERNAME": "swingshree9@gmail.com",
      "PASSWORD": "Shree@99"
    }
  }'

Expected Response:

{
  "AuthenticationResult": {
    "AccessToken": "eyJraWQiOiJ...(long token)...xyz",
    "IdToken": "eyJraWQiOiJ...(long token)...abc",
    "RefreshToken": "eyJjdHkiOiJ...(long token)...def",
    "ExpiresIn": 3600,
    "TokenType": "Bearer"
  }
}

Important: Copy the AccessToken and IdToken values.

Step 3: Update Configuration

Once you have your User Pool ID, update application.properties:

aws.cognito.region=ap-southeast-1
aws.cognito.userPoolId=ap-southeast-1_YOUR_POOL_ID_HERE
aws.cognito.jwks.url=https://cognito-idp.ap-southeast-1.amazonaws.com/ap-southeast-1_YOUR_POOL_ID_HERE/.well-known/jwks.json

Step 4: Test the User Service

Start the Service

./gradlew bootRun

Test Create/Sync User

curl -X POST 'http://localhost:8080/create-user' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN_HERE' \
  --header 'X-Id-Token: YOUR_ID_TOKEN_HERE'

Replace YOUR_ACCESS_TOKEN_HERE with the actual AccessToken from Step 2.

Expected Success Response (200):

{
  "userid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "email": "swingshree9@gmail.com",
  "preferenceId": null
}

The userid will be the Cognito subject (user's unique ID in Cognito).

Expected Error if User Pool ID is Wrong (400):

{
  "error": "Token verification failed: Invalid token issuer"
}

Step 5: Verify User Creation

Check H2 Console

  1. Open: http://localhost:8080/h2-console
  2. Use JDBC URL: jdbc:h2:mem:testdb
  3. Username: sa, Password: (leave empty)
  4. Run query:
    SELECT * FROM app_user;

You should see your user with:

Get User by ID

curl -X GET 'http://localhost:8080/api/users/YOUR_USER_ID'

Replace YOUR_USER_ID with the userid from the create-user response.

Complete Testing Workflow

1. Sign in to Cognito and extract tokens

COGNITO_RESPONSE=$(curl -s -X POST 'https://cognito-idp.ap-southeast-1.amazonaws.com/' \
  --header 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
  --header 'Content-Type: application/x-amz-json-1.1' \
  --data '{
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "1d1jkchdvgt5tldbb0hivruird",
    "AuthParameters": {
      "USERNAME": "swingshree9@gmail.com",
      "PASSWORD": "Shree@99"
    }
  }')

# Extract tokens (requires jq)
ACCESS_TOKEN=$(echo $COGNITO_RESPONSE | jq -r '.AuthenticationResult.AccessToken')
ID_TOKEN=$(echo $COGNITO_RESPONSE | jq -r '.AuthenticationResult.IdToken')

echo "Access Token: $ACCESS_TOKEN"
echo "ID Token: $ID_TOKEN"

2. Create/sync user in your service

curl -X POST 'http://localhost:8080/create-user' \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header "X-Id-Token: $ID_TOKEN"

3. Verify idempotency (call again)

# Should return the same user, not create a duplicate
curl -X POST 'http://localhost:8080/create-user' \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  --header "X-Id-Token: $ID_TOKEN"

Troubleshooting

Error: "Token verification failed: Invalid token issuer"

Cause: User Pool ID in configuration doesn't match the one that issued the token.

Solution:

  1. Decode your access token at https://jwt.io
  2. Look at the iss claim: https://cognito-idp.ap-southeast-1.amazonaws.com/ap-southeast-1_XXXXXXXXX
  3. The part after the last / is your User Pool ID
  4. Update application.properties with this value

Error: "Connection refused" or "Failed to fetch JWKS"

Cause: Service can't reach AWS Cognito JWKS endpoint.

Solution: Check internet connectivity and firewall rules.

Error: "JWT signature verification failed"

Possible causes:

  1. Token is expired (tokens expire after 1 hour by default)
  2. Token is from a different User Pool
  3. Token is malformed or truncated

Solution: Get a fresh token from Cognito and try again.

Error: "Authorization header is required"

Cause: Missing or malformed Authorization header.

Solution: Ensure header is: Authorization: Bearer <token> with space after "Bearer".

Postman Collection

1. Cognito Sign In

  • Method: POST
  • URL: https://cognito-idp.ap-southeast-1.amazonaws.com/
  • Headers:
    • X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth
    • Content-Type: application/x-amz-json-1.1
  • Body (raw JSON):
    {
      "AuthFlow": "USER_PASSWORD_AUTH",
      "ClientId": "1d1jkchdvgt5tldbb0hivruird",
      "AuthParameters": {
        "USERNAME": "swingshree9@gmail.com",
        "PASSWORD": "Shree@99"
      }
    }
  • Test Script (to auto-extract tokens):
    var jsonData = pm.response.json();
    pm.environment.set("access_token", jsonData.AuthenticationResult.AccessToken);
    pm.environment.set("id_token", jsonData.AuthenticationResult.IdToken);

2. Create User

  • Method: POST
  • URL: http://localhost:8080/create-user
  • Headers:
    • Authorization: Bearer {{access_token}}
    • X-Id-Token: {{id_token}}

3. Get User by ID

  • Method: GET
  • URL: http://localhost:8080/api/users/{{user_id}}
  • Note: Set user_id from the create-user response

Next Steps

  1. ✅ Find your User Pool ID
  2. ✅ Update application.properties
  3. ✅ Restart the service
  4. ✅ Test with real tokens
  5. ✅ Verify user creation in H2 console
  6. ✅ Test from Flutter app

Integration with Flutter App

Your Flutter app should:

  1. Sign in with Cognito (you're already doing this)
  2. Store the access_token
  3. Call your user service:
    final response = await http.post(
      Uri.parse('https://your-service-url/create-user'),
      headers: {
        'Authorization': 'Bearer $accessToken',
        'X-Id-Token': '$idToken',
      },
    );
  4. Store the userId from response for future API calls

The user service will:

  • ✅ Verify the token signature
  • ✅ Create user on first sign-in
  • ✅ Return existing user on subsequent sign-ins
  • ✅ Use Cognito subject as the user ID