douqixia7942 2018-10-26 19:43
浏览 111
已采纳

如何从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.

  • 写回答

1条回答 默认 最新

  • dongyi2534 2018-10-26 22:23
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?