Can Lombok exclude the value but still print the field name?

Viewed 639

I'm working on a Java application which handles multiple sensitive values. We are using Lombok, and have a lot of data classes which look like this the below. However, it's confusing to see these classes in the log with no indication that they contain some critical fields, as the generated toString will 100% ignore the excluded fields. Is it possible to have Lombok print something like clientSecret=<HIDDEN> without writing a custom toString for each class?

/** data we will send to token endpoint */
@Data
public class TokenReq {
    private String grantType;

    private String code;

    private String clientId;

    @ToString.Exclude
    private String refreshToken;

    @ToString.Exclude
    private String clientSecret;

    private String redirectUri;
}
2 Answers

You can exclude the field that should be masked and include a helper method that returns the masked value:

@Data
public class TokenReq {

    @ToString.Exclude
    private String clientSecret;

    @ToString.Include(name="clientSecret")
    private String hiddenClientSecretForToString() {
        return "<HIDDEN>";
    }
}

As said in the comment this is how I did a while ago, it needs some more work probably, but here is the idea:

interface ToString {

    default String innerToString(String... exclusions) {
        Method[] allMethods = getClass().getDeclaredMethods();
        return Arrays.stream(allMethods)
                     .filter(x -> x.getName().startsWith("get"))
                     .map(x -> {
                         if (Arrays.stream(exclusions).anyMatch(y -> ("get" + y).equalsIgnoreCase(x.getName()))) {
                             return x.getName().substring(3) + " = <HIDDEN>";
                         }

                         try {
                             return x.getName().substring(3) + " = " + x.invoke(this);
                         } catch (Exception e) {
                             throw new RuntimeException(e);
                         }
                     })
                     .collect(Collectors.joining(" "));

    }
}

And a class:

static class Person implements ToString {

    private String name;
    private String password;

    // constructor/getter or lombok annotations

    public String toString() {
        return innerToString("password");
    }
}

And then usage:

public static void main(String[] args) {
    Person p = new Person("eugene", "password");
    System.out.println(p);
}
Related