Does Cognito provide the Id token that is returned by Google ?

0

Hello guys,

I'm currently using Cognito preSignUp trigger to store users in my own database. To do so, I want to access the ID token that is generated by Google and save it in the database but I can't access it. I have found resources that state that identities attribute in the event has the ID token but Imy event doesn't have such an attribute.

So my question is does Cognito provide the Id token that is returned by Google or there is no way for me to access it?

Note: The event has all the data that I require and mapped (firstName, LastName,etc...)

Thank you in advance!

Karim
asked 2 months ago114 views
1 Answer
0

When using Amazon Cognito with federated identity providers like Google, the ID token issued by Google is not directly accessible in the preSignUp trigger. The preSignUp Lambda trigger is invoked before the user is confirmed in the user pool, and at this stage, Cognito does not pass the ID token from the identity provider (Google) in the event object.

However, there are alternative ways to handle the requirement to access and store the Google ID token in your database. Here are some approaches:

  1. Use the Post Authentication Trigger The Post Authentication trigger is invoked after the user has been authenticated and the token has been issued. At this point, you can access the tokens and store them in your database.
def lambda_handler(event, context):
    user_attributes = event['request']['userAttributes']
    user_name = user_attributes['name']
    email = user_attributes['email']
    
    # If the user authenticated through a federated identity provider, get the identity provider information
    if 'identities' in user_attributes:
        identities = user_attributes['identities']
        for identity in identities:
            if identity['providerName'] == 'Google':
                google_id_token = identity['issuer'] # This will give you the token from Google
                # Store google_id_token in your database
                
    return event
  1. Use the Custom Authentication Flow You can create a custom authentication flow that retrieves the Google ID token on the client side and then sends it to your backend, where you can process and store it in your database.

Here’s a high-level overview of how this can be done:

Client Side:

Use Google Sign-In to authenticate the user and get the ID token. Send the ID token to your backend service. Backend Side:

Verify the ID token with Google to ensure it is valid. Store the verified ID token in your database. Use the Cognito Admin API to create or update the user in Cognito. Example Client-Side Code

function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;
  
  // Send ID token to the backend
  fetch('https://your-backend.example.com/store-google-token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ id_token: id_token })
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
}

Example Backend Code

from google.oauth2 import id_token
from google.auth.transport import requests

def store_google_token(request):
    id_token_str = request.json['id_token']
    
    # Verify the token with Google
    try:
        id_info = id_token.verify_oauth2_token(id_token_str, requests.Request(), 'YOUR_GOOGLE_CLIENT_ID')
        user_id = id_info['sub']
        email = id_info['email']
        
        # Store the token and user information in your database
        # (Assuming you have a function `store_user_token` to handle database operations)
        store_user_token(user_id, email, id_token_str)
        
        return {'status': 'success'}
    except ValueError as e:
        return {'status': 'error', 'message': str(e)}

In summary

PreSignUp Trigger: Does not provide access to the ID token from Google. Post Authentication Trigger: Can be used to get identity provider information after authentication. Custom Authentication Flow: Use client-side Google Sign-In and send the ID token to the backend for verification and storage.

profile picture
EXPERT
answered 2 months ago
  • Can I use the Post Confirmation instead of Post Authentication as the Post Authentication will not be triggered in the first sign in using Google or Facebook ?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions