Java 中针对 Cognito 的 AWS Lambda 响应

Bak*_*alf 4 java amazon-web-services amazon-cognito aws-sdk aws-lambda

如何用 Java 编写“AWS Lambda 响应”以使 Cognito 满意?

像这样的东西被传递给 lambda 函数

{
"version": number,
"triggerSource": "string",
"region": AWSRegion,
"userPoolId": "string",
"callerContext": 
    {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
"request":
    {
        "userAttributes": {
            "string": "string",
            ....
        }
    },
"response": {}
}
Run Code Online (Sandbox Code Playgroud)

现在我需要用 Java 做出响应并发送回 Cognito。目前,Cognito 抛出“InvalidLambdaResponseException”。

下面的Java代码只返回事件..

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

Vas*_*kis 5

你只需要一个这样的类:

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 { }

}
Run Code Online (Sandbox Code Playgroud)

序列化后将如下所示:

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

并将其作为 lambda 的输入。它可能需要一些更改,但这是 PostAuthentication lambda 模板的示例