Mask sensitive data with custom Jackson annotations
2018-06-29 / modified at 2025-01-29 / 388 words / 2 mins
In this article, we’ll see how to use custom Jackson annotations to mask sensitive data with asterisks.
Here is a User
, in which the tel
field contains a customer’s privacy information that may not be allowed to persist on the server under certain regulations (such as GDPR).
1 | public class User { |
Test case
1 | User user = new User(); |
Solution
Step 1: Create an annotation
1 |
|
Step 2: Wrap the field with a annotation.
1 | public class User { |
Step 3: Create a custom serializer
1 | public class AsteriskSerializer extends StdSerializer<Object> implements ContextualSerializer { |
Updated Test case:
1 | User user = new User(); |
Now, you can safely log the user data without exposing sensitive information.
Other Recommendations
Here are some other potential leaks of which should be taken care
- SQL: Be careful while logging SQL queries with frameworks like Mybatis. For example,
select user from users where email = ?
may leak parameters. - HTTP Header: Avoid printing sensitive headers (e.g., authentication tokens, X-Forward-For) in logs, especially when using interceptors like OkHttp.
- Socket: Validate payload before logging
readline()
output. - Third-party crash SDKs: Restrict outbound traffic when possible, as it’s hard to prevent data smuggling.