我正在学习https://serverless-stack.com/教程,该教程使用无服务器框架创建一个DynamoDB,它将对象插入到API表中,并将它们与经过身份验证的AWS Cognito用户相关联。我正在尝试将Node.js代码转换为Java,但是在获取Cognito标识时遇到了一个问题,如on this page所示
userId: event.requestContext.identity.cognitoIdentityId,
我希望以下几行Java代码是等效的:
final CognitoIdentity identity = context.getIdentity();
final String userId = identity.getIdentityId();
但是userId
是空的。
我使用aws-api-gateway-cli-test
实用程序使用Cognito用户的凭据调用我的API,如on this page所示。身份验证通过,但处理程序中的userId
为空。
这是我的函数:
package com.mealplanner.function;
import java.util.Map;
import com.amazonaws.services.lambda.runtime.CognitoIdentity;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mealplanner.dal.MealRepository;
import com.mealplanner.domain.Meal;
import com.serverless.ApiGatewayResponse;
public class CreateMealHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
@Override
public ApiGatewayResponse handleRequest(final Map<String, Object> request, final Context context) {
try {
final CognitoIdentity identity = context.getIdentity();
final String userId = identity.getIdentityId();
final JsonNode body = new ObjectMapper().readTree((String) request.get("body"));
final MealRepository repository = new MealRepository();
final Meal meal = new Meal();
meal.setUserId(userId);
meal.setDescription(body.get("description").asText());
repository.save(meal);
return ApiGatewayResponse.builder()
.setStatusCode(200)
.setObjectBody(meal)
.build();
} catch (final Exception e) {
final String errorText = String.format("Error saving meal with request [%s]", request);
LOGGER.error(errorText, e);
return ApiGatewayResponse.builder()
.setStatusCode(500)
.setObjectBody(errorText)
.build();
}
}
}
这是serverless.yml中的函数定义:
createMeal:
handler: com.mealplanner.function.CreateMealHandler
events:
- http:
path: /meals
method: post
cors: true
authorizer: aws_iam
我是否遗漏了一些配置,或者我没有正确转换Node.js代码?
如果我遗漏了任何相关信息,可以在这里找到完整的代码:https://github.com/stuartleylandcole/meal-planner/tree/add-users。我将使用缺失的任何信息更新此问题,以确保所有相关信息都是独立的。
https://stackoverflow.com/questions/51433042
复制相似问题