Passing userId from angular using cognito user pool to aws lambda

575 Views Asked by At

I have an angular frontend shipping form and when I click submit, the values reach the backend, but not the userId. My app authenticates with the cognito user pool and I get the token. enter image description here

but I can't seem to pass the userId.

enter image description here

I added $context.authorizer.principalId per the documentation. I also tried $context.authorizer.claims.userId but same issue.

enter image description here

shipping.service.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Subject, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from '../../auth.service';

@Injectable()
export class ShippingService {
  dataEdited = new BehaviorSubject<boolean>(false);
  dataIsLoading = new BehaviorSubject<boolean>(false);
  dataLoaded = new Subject<[]>();
  dataLoadFailed = new Subject<boolean>();
  userData;
  constructor(private http: HttpClient, private authService: AuthService) {
  }

  onStoreData(data) {
    this.dataLoadFailed.next(false);
    this.dataIsLoading.next(true);
    this.dataEdited.next(false);
    this.userData = data;
    console.log("DATA", data)


    this.authService.getAuthenticatedUser().getSession((err, session) => {
      console.log(session);
      let headers = new HttpHeaders();
      headers.append('Authorization', session.getIdToken().getJwtToken());
      headers.append('Accept', 'application/json');
      headers.append('Access-Control-Allow-Origin', '*');
      let options = { headers: headers, reportProgress: true };

      if (err) {
        return;
      }
      this.http.post('https://nx96w6r3oc.execute-api.us-east-1.amazonaws.com/dev/shipping', data, options)

        .subscribe(
          (result) => {
            this.dataLoadFailed.next(false);
            this.dataIsLoading.next(false);
            this.dataEdited.next(true);
          },
          (error) => {
            this.dataIsLoading.next(false);
            this.dataLoadFailed.next(true);
            this.dataEdited.next(false);
          }
        );
    });
  }
}

aws lambda function

const AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler =  (event, context, callback) => {
    console.log(event)
    const params = {
    Item:{
        "UserId": {
            S: event.userId
        },
        "FirstName": {
            S: event.firstName
        },
        "LastName": {
            S: event.lastName
        },
        "Address1": {
            S: event.address1
        },
         "Address2": {
            S: event.address1
        },
         "State": {
            S: event.state
        },
         "City": {
            S: event.city
        }, 
        "Zip": {
            S: event.zip
        }
        
    },
    TableName: "shipping"
    };
    
 dynamodb.putItem(params, function(err, data) {
    
   if (err) {
       console.log(err)
    callback(err);
   } 
   else{ 
           console.log(data)
callback(null, data);
   }
 });


   
 };

UPDATE:

A couple things I've noticed so far is that identity is undefined when outputting console.log(context) in lambda function. enter image description here

Also I did a console.log(session) inside angular service above to validate user_id is there enter image description here

I'm super confused on why the userId shows up as blank string userId: '' in output. I appreciate any help!

2

There are 2 best solutions below

0
On BEST ANSWER

A couple things were the issue. I resolved the problem by

  1. changing my integration request mapping template userId value "userId": "$context.authorizer.claims.sub" for my user pool userId
  2. Another thing I did to resolve it fully was add an authorizer I created to the method request.

I was able to successfully store data into dynamodb after making these changes.

enter image description here

5
On

you can get that you want via:

context.identity.cognitoIdentityId