I'm working on page that allows users to edit profile info. I want them to be able to edit their public info, but not allow them to change system flags such as their user type.
This is implemented with Spring MVC (3.0). The User object has typical fields such as firstName
, lastName
, email
(all should be editable) and a boolean administrator
(which should not be editable.
My method looks something like this:
@RequestMapping(method = RequestMethod.POST)
public String doEdit(
@ModelAttribute("user") User user,
BindingResult result,
ModelMap model)
throws IOException
{
// validate, blah blah
// save user object
// return page
}
My form includes fields firstName
, lastName
etc and seemed to work fine.
The problem is that if a malicious user posts a query with the parameter administrator
as "true" they can set this field when they shouldn't.
I know I can create a separate "form" object with just the fields I want to change and use that for the automatic binding. (the copy over the data). The problem is that I have a lot of places which use this technique. (for the user and other objects). It'd be a hassle to maintain when I want to add fields.
Is there a way to use annotations or other techniques in Spring MVC to whitelist parameters and prevent changes to arbitrary domain object properties?
The DataBinder has two properties named allowedFields
and disallowedFields
that define what to (dis)allow for binding. Just use that in your @InitBinder
method:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("administrator");
}
You could filter the request with the "!myParam" style expressions, to indicate that the specified parameter is not supposed to be present in the request.
@RequestMapping(params="!administrator")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With