user352290
user352290

Reputation: 1298

How to redact username, password information from RestTemplate logs

How to redact username, password information from RestTemplate logs in a Spring Boot App

19:16:30.017 [http-nio-9550-exec-7] DEBUG o.s.web.client.RestTemplate - Writing [{grant_type=[password], client_id=[eve-client], client_secret=[v8nhI8YzyOLmP3tPyFwrMsP1rSCHOZBE], scope=[offline_access], username=[john], password=[FooBar..][]}] as "application/x-www-form-urlencoded"

Upvotes: 0

Views: 48

Answers (1)

Julien Antony
Julien Antony

Reputation: 351

Unless you want to implement a custom logwriter based on some regexp, I would suggest to use https://github.com/zalando/logbook?tab=readme-ov-file#spring-boot-starter.

It integrates nicely with RestTemplate. From there you could configure your own BodyFilter

class CustomUrlEncodedBodyFilter implements BodyFilter {
  private final Set<String> namesToObfuscate;
  private static final Predicate<String> FORM_URL_ENCODED =
      MediaTypeQuery.compile("application/x-www-form-urlencoded");

  public CustomUrlEncodedBodyFilter(Set<String> namesToObfuscate) {
    this.namesToObfuscate = namesToObfuscate;
  }

  @Override
  public String filter(@Nullable final String contentType, final String body) {
    return FORM_URL_ENCODED.test(contentType) ? obfuscate(body) : body;
  }

  private String obfuscate(final String body) {
    // Do the obfuscate here, ie parse body (should probably works with java.net.URL?) and replace values of items listed in namesToObfuscate
    return body;
  }
}

@Bean
public BodyFilter bodyFilter() {
    return merge(
            defaultValue(), 
            new CustomUrlEncodedBodyFilter(Set.of("username","password"))); //You can extract those properties in external file
}

Upvotes: 0

Related Questions