Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect specific fields when binding in Spring

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?

like image 269
Will Glass Avatar asked Feb 16 '11 22:02

Will Glass


2 Answers

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");
}
like image 180
Costi Ciudatu Avatar answered Oct 12 '22 11:10

Costi Ciudatu


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")
like image 44
Julian Bonilla Avatar answered Oct 12 '22 11:10

Julian Bonilla