繁体   English   中英

使用杰克逊掩盖json领域

[英]Mask json fields using jackson

我正在尝试使用jackson进行序列化时屏蔽敏感数据。

我尝试过使用@JsonSerialize和自定义注释@Mask。

Mask.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Mask {
  String value() default "XXX-DEFAULT MASK FORMAT-XXX";
}

Employee.java

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Map;

public class Employee {

  @Mask(value = "*** The value of this attribute is masked for security reason ***")
  @JsonSerialize(using = MaskStringValueSerializer.class)
  protected String name;

  @Mask
  @JsonSerialize(using = MaskStringValueSerializer.class)
  protected String empId;

  @JsonSerialize(using = MaskMapStringValueSerializer.class)
  protected Map<Category, String> categoryMap;

  public Employee() {
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getEmpId() {
    return empId;
  }

  public void setEmpId(String empId) {
    this.empId = empId;
  }

  public Map<Category, String> getCategoryMap() {
    return categoryMap;
  }

  public void setCategoryMap(Map<Category, String> categoryMap) {
    this.categoryMap = categoryMap;
  }
}

Category.java

public enum Category {
  @Mask
  CATEGORY1,
  @Mask(value = "*** This value of this attribute is masked for security reason ***")
  CATEGORY2,
  CATEGORY3;
}

MaskMapStringValueSerializer.java

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Map;

public class MaskMapStringValueSerializer extends JsonSerializer<Map<Category, String>> {

  @Override
  public void serialize(Map<Category, String> map, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    jsonGenerator.writeStartObject();

    for (Category key : map.keySet()) {
      Mask annot = null;
      try {
        annot = key.getClass().getField(key.name()).getAnnotation(Mask.class);
      } catch (NoSuchFieldException e) {
        e.printStackTrace();
      }

      if (annot != null) {
        jsonGenerator.writeStringField(((Category) key).name(), annot.value());
      } else {
        jsonGenerator.writeObjectField(((Category) key).name(), map.get(key));
      }
    }

    jsonGenerator.writeEndObject();

  }
}

MaskStringValueSerializer.java

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

public class MaskStringValueSerializer extends StdSerializer<String> implements ContextualSerializer {
  private Mask annot;

  public MaskStringValueSerializer() {
    super(String.class);
  }

  public MaskStringValueSerializer(Mask logMaskAnnotation) {
    super(String.class);
    this.annot = logMaskAnnotation;
  }

  public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    if (annot != null && s != null && !s.isEmpty()) {
      jsonGenerator.writeString(annot.value());
    } else {
      jsonGenerator.writeString(s);
    }
  }

  public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
    Mask annot = null;
    if (beanProperty != null) {
      annot = beanProperty.getAnnotation(Mask.class);
    }
    return new MaskStringValueSerializer(annot);

  }
}

MaskValueTest.java

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class MaskValueTest {


  public static void main(String args[]) throws Exception{
    Employee employee = new Employee();

    employee.setName("John Doe");
    employee.setEmpId("1234567890");
    Map<Category, String> catMap = new HashMap<>();
    catMap.put(Category.CATEGORY1, "CATEGORY1");
    catMap.put(Category.CATEGORY2, "CATEGORY2");
    catMap.put(Category.CATEGORY3, "CATEGORY3");
    employee.setCategoryMap(catMap);

    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));
  }
}

输出 -

{
  "name" : "*** The value of this attribute is masked for security reason ***",
  "empId" : "XXX-DEFAULT MASK FORMAT-XXX",
  "categoryMap" : {
    "CATEGORY1" : "XXX-DEFAULT MASK FORMAT-XXX",
    "CATEGORY2" : "*** The value of this attribute is masked for security reason ***",
    "CATEGORY3" : "CATEGORY3"
  }
}
  • 结果是按照预期,然而,这似乎是静态掩蔽。
  • 目的是仅在需要时屏蔽,例如在日志中打印时应该屏蔽所有这些敏感数据。
  • 如果我必须发送这个json用于文档索引,其值应该是原样,这个实现失败了。

我正在寻找一个基于注释的解决方案,我可以使用JsonSerializers初始化的2个不同的ObjectMapper实例。

您可以创建模块来捆绑序列化程序并使用objectmapper注册模块,而不是使用MaskStringValueSerializer.java,这最终将允许您拥有两个不同的objectmapper实例。

创建一个模块以捆绑序列化程序

public class MaskingModule extends SimpleModule {
    private static final String NAME = "CustomIntervalModule";
    private static final VersionUtil VERSION_UTIL = new VersionUtil() {};

    public MaskingModule() {
      super(NAME, VERSION_UTIL.version());
      addSerializer(MyBean.class, new MaskMapStringValueSerializer());
    }
}

使用ObjectMapper注册模块并使用它

 ObjectMapper objectMapper = new ObjectMapper().registerModule(new MaskingModule());
 System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee));

您还可以扩展Object Mapper,注册模块并使用它

public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
      registerModule(new MaskingModule());
    }
  }


 CustomObjectMapper customObjectMapper = new CustomObjectMapper ();
 System.out.println(customObjectMapper .writerWithDefaultPrettyPrinter().writeValueAsString(employee));

取出@JsonSerialize注释,并把如何处理的逻辑@Mask在注释Module ,例如,有它添加AnnotationIntrospector

您现在可以选择是否调用registerModule(Module module)

至于编写模块,我会把它留给你。 如果您对此有任何疑问,请提出另一个问题。

为什么不使用两个参数作为原始值,一个参数作为屏蔽值。 例如,在这种情况下,您可以使用String name和String maskedName。 然后,对于日志记录,您可以使用屏蔽值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM