在AWS CDK(Java)中创建StatementProperty时uriPath字段如何定义?
解决AWS CDK Java中WAF WebACL uriPath空对象定义问题
在AWS CDK 2.51.1的Java实现中,要为FieldToMatchProperty的uriPath字段定义符合要求的空对象,你可以用以下两种可行方式:
方案1:使用Java自带的空不可变Map
这是最简便的实现方式,无需额外依赖,Jackson会自动将空Map序列化为标准JSON空对象{}:
import java.util.Map; // 定义符合要求的空对象 Object emptyUriPath = Map.of(); StatementProperty apiV1Order = StatementProperty.builder() .byteMatchStatement(ByteMatchStatementProperty.builder() .searchString("/the/path/to/allow") .positionalConstraint("STARTS_WITH") .fieldToMatch(FieldToMatchProperty.builder() .uriPath(emptyUriPath) .build()) .textTransformations(List.of(TextTransformationProperty.builder() .priority(0) .type("LOWERCASE") .build())) .build()) .build();
方案2:使用Jackson的ObjectNode
CDK底层依赖Jackson,直接创建空ObjectNode也能满足序列化要求:
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.JsonNodeFactory; // 定义符合要求的空对象 Object emptyUriPath = JsonNodeFactory.instance.objectNode(); // 后续规则构建代码与方案1一致 StatementProperty apiV1Order = StatementProperty.builder() .byteMatchStatement(ByteMatchStatementProperty.builder() .searchString("/the/path/to/allow") .positionalConstraint("STARTS_WITH") .fieldToMatch(FieldToMatchProperty.builder() .uriPath(emptyUriPath) .build()) .textTransformations(List.of(TextTransformationProperty.builder() .priority(0) .type("LOWERCASE") .build())) .build()) .build();
之前尝试失败的原因
new Object():序列化后会包含类名等冗余信息,不是WAF API要求的标准JSON空对象"{}":属于字符串类型,而WAF API要求该字段为对象类型,类型不匹配- Gson的
JsonObject:CDK底层使用Jackson做序列化,Gson对象无法被正确识别序列化
内容的提问来源于stack exchange,提问作者Peter Störmer
相关产品推荐
相关产品推荐

