首页 > 解决方案 > 如何使用 zalando.logbook 屏蔽 xml 正文中的敏感数据

问题描述

Zalando.LogBook 有一些默认的掩码过滤器,但我还没有找到一个用于 xml 正文的过滤器。我需要在 xml 正文中屏蔽密码字段 ( <password>1234<\password>-> )。<password>masked<\password>是否有任何机构实现了可以在 xml 主体中屏蔽密码的主体过滤器?

  @Bean
  public Logbook getLogBook() {
    final Set<String> properties = new HashSet<>(Arrays.asList("password");

    return Logbook.builder()
        .bodyFilter(BodyFilters.replaceFormUrlEncodedProperty(properties, "<masked>"))
                                                 .build();
  }

标签: javaspring

解决方案


日志源中有一个用于压缩 XML 的类:org.zalando.logbook.CompactingXmlBodyFilter.

只需复制并粘贴它,然后像在removeEmptyTextNodes().

例如:

class LogbookXmlBodyPasswordFilter implements BodyFilter {
    [...]
    private void removePasswordTag(final Document document) throws Exception {
            final XPathFactory xPathFactory = XPathFactory.newInstance();
            final XPath xpath = xPathFactory.newXPath();
            NodeList nodeList = (NodeList) xpath.evaluate("Password", document, XPathConstants.NODESET);
    
            for (int i = 0; i < nodeList.getLength(); i++) {
                final Node node = nodeList.item(i);
                node.getParentNode().removeChild(node);
            }
        }
}

此方法将从 XML 中删除任何 <Password>标记。

然后你可以像这样使用它:

 @Bean
 public BodyFilter bodyFilter() {
     return logbookXmlBodyPasswordFilter();
 }

 public static BodyFilter logbookXmlBodyPasswordFilter() {
     return new LogbookXmlBodyPasswordFilter();
 }

推荐阅读