Avoid security loopholes using @JsonView

Written by paruldhingra | Published 2020/10/17
Tech Story Tags: technology | software-development | web-development | programming | spring-boot | javascript | javascript-top-story | understanding-javascript | web-monetization

TLDR Use @JsonView to limit or control fields display for different users. Don't expose more than you think needs exposing. Avoid security loopholes using @JonView. Use the same annotations to annotate the fields you want to receive when updating. For example, in userForm, annotate with userForm(UpdateUser.class) the fields. The same annotations are used in the handler, as below:.glygly.glyphobe.globe-globe: Glyphobe@ paruldhingra Software Enginner.via the TL;DR App

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.

What is @JsonView and how to use it?

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.

Conclusion:

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.

Written by paruldhingra | Software Enginner | Blogger | A brain ambidextrous geek | Machine Learning Enthusiasts
Published by HackerNoon on 2020/10/17