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

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?