AWS Lambda response in Java for Cognito

我只是一个虾纸丫 提交于 2020-01-14 05:45:26

问题


How can I write an "AWS Lambda response" in Java so that Cognito is happy?

Something like this is passed to the lambda function

{
"version": number,
"triggerSource": "string",
"region": AWSRegion,
"userPoolId": "string",
"callerContext": 
    {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
"request":
    {
        "userAttributes": {
            "string": "string",
            ....
        }
    },
"response": {}
}

Now I need to make the response in Java.. and send back to Cognito. At the moment Cognito throws an "InvalidLambdaResponseException".

Java code below just returns the event..

public class LambdaFunctionHandler implements RequestHandler<CognitoEvent, CognitoEvent> 
{
    @Override
    public CognitoEvent handleRequest(CognitoEvent arg0, Context arg1) 
    {
        return arg0;
    }
}

回答1:


You just need a class like this:

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.Map;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonSerialize
public class Example {
    private int version;
    private String triggerSource;
    private String region;
    private String userPoolId;
    private Map<String, String> callerContext;
    private Request request;
    private Response response;

    @Getter
    @Setter
    @JsonSerialize
    public static class Request {
        private Map<String, String> userAttributes;
        public Request(Map<String, String> userAttr) {
            userAttributes = userAttr;
        }
    }

    @Getter
    @Setter
    @JsonSerialize
    public static class Response { }

}

That after you serialize will look like this:

{
  "version" : 1,
  "triggerSource" : "trigger",
  "region" : "us-east-1",
  "userPoolId" : "user-pool-id",
  "callerContext" : {
    "some-key" : "some-value"
  },
  "request" : {
    "userAttributes" : {
      "name" : "Michael J Leonard"
    }
  },
  "response" : { }
}

And have this as an input to your lambda. It might require some changes but this is an example of a template for the PostAuthentication lambda



来源:https://stackoverflow.com/questions/46526687/aws-lambda-response-in-java-for-cognito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!