Don’t expose more than you think needs exposing.
If a certain property on an object is not useful to a consumer and internal to your business, then don’t return it.
Sometimes you may like to reuse the same form class for receiving request data in multiple handlers/controllers. For example, say you have this UserForm for user registration:
where the user registration handler looks as below:
Now, say you have another handler for updating users, looking as below:
Noticed the same userForm above?
Consequently, someone can call the end-point with the unrequired fields(i.e. email & password), thus injecting those into your form!
So to prevent it, we can use @JsonView annotation.
We can use @JsonView to limit or control fields display for different users. To prevent injection discussed above, first define a marker interface as below:
Then, in userForm, annotate with @JsonView(UpdateUser.class) the fields you want to receive when updating:
Finally, use the same annotation in the handler, as below:
That’s all you need to prevent the injection.
This is very useful particularly when you are reusing the domain classes as forms. For example, if you reuse a User domain class as the form and then save it straight to the database, you can get hacked.
When registering, what if a malicious user adds an id or a createdDate field, which gets injected instead of auto-generated?
Take a few minutes and ponder the question before you jump to a conclusion.
I hope you learned something from this article.
Thanks for reading, and happy coding!. Do share your feedback and suggestions in the comments section below.