如何从Go Lambda中获取当前的Cognito用户

问题描述:

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.

我很难从我的lambda函数中获取当前的Cognito用户属性,即 走。 我目前正在做: p>

  userAttributes = request.RequestContext.Authorizer [“ claims”] 
  code>  pre> 
 
 

如果我想获取电子邮件: p>

  userEmail = request.RequestContext.Authorizer [“ claims”]。(map [string] interface {})[“ email”]。  (字符串)
  code>  pre> 
 
 

我认为这不是好方法,甚至不是可以接受的方法-它必须有更好的方法。 p> div>

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).