Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current cognito user from within go lambda

I'm having a hard time to get the current Cognito user attributes from within my lambda function, that is written in Go. I'm currently doing:

userAttributes = request.RequestContext.Authorizer["claims"]

And if I want to get the email:

userEmail = request.RequestContext.Authorizer["claims"].(map[string]interface{})["email"].(string)

I don't think this is a good way or even an acceptable way - it must have a better way to do it.

like image 307
Evanusso Avatar asked Oct 26 '18 19:10

Evanusso


People also ask

How do I find my Lambda Cognito username?

In order to get the identityId of a Cognito user in a Lambda function we have to call the getId method on the CognitoIdentity class. Let's look at the complete code of a helper method, which retrieves and returns the identityId of a Cognito user. Copied!

How do you connect lambda to Cognito?

To add a user pool Lambda trigger with the console Go to the Amazon Cognito console , and then choose User Pools. Choose an existing user pool from the list, or create a user pool. Choose the User pool properties tab and locate Lambda triggers. Choose Add a Lambda trigger.

How do you add a Cognito user to Dynamodb using lambda?

Access your IAM Management console and select Roles from the left menu. Click Create role and select the AWS Service Lambda role. Once both are highlighted, click Next: Permissions. Name your role whatever you want, as long as it's recognizable to you, and click Create role.

What is sub in Cognito?

Cognito uses both cognitoId and sub to identify a user. This project from the official awslabs uses the cognitoId as primary key in the database tables to link data to a user object, but the documentation about sub clearly states: sub : the UUID of the authenticated user. This is not the same as username .


Video Answer


1 Answers

You can use 3rd party library to convert map[string]interface{} to a concrete type. Check the mitchellh/mapstructure library, it will help you to implement in a better way.

So, you could improve your code with this code :

import "github.com/mitchellh/mapstructure"

type Claims struct {
    Email string
    // other fields
    ID int
}

func claims(r request.Request) (Claims, error) {
    input := r.RequestContext.Authorizer["claims"]
    output := Claims{}
    err := mapstructure.Decode(input, &output)

    if err != nil {
        return nil, err
    }

    return output, nil
}

And somewhere in your handlers, you could get your claims by calling this method

func someWhere(){

    userClaims, err := claims(request)

    if err != nil {
        // handle
    }

    // you can now use : userClaims.Email, userClaims.ID
}

Don't forget to change func claims request parameter type according to yours (r parameter).

like image 146
Maxian Nicu Avatar answered Sep 21 '22 15:09

Maxian Nicu