How to fix Mass Assignment: Insecure Binder Configuration (API Abuse, Structural) in java

dildeepak picture dildeepak · Dec 22, 2017 · Viewed 15.8k times · Source

I have a Controller class with the below two methods for finding a doctors (context changed). Getting the Mass Assignment: Insecure Binder Configuration (API Abuse, Structural) error on both methods.

@Controller
@RequestMapping(value = "/findDocSearch")
public class Controller {

    @Autowired
    private IFindDocService findDocService;

    @RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseBody
    public List<FindDocDTO> findDocByName(FindDocBean bean) {
        return findDocService.retrieveDocByName(bean.getName());
    }

    @RequestMapping(value = "/byLoc", method = RequestMethod.GET)
    @ResponseBody
    public List<FindDocDTO> findDocByLocation(FindDocBean bean) {
        return findDocService.retrieveDocByZipCode(bean.getZipcode(),
        bean.getDistance());
    }
}

and my Bean is :

public class FindDocBean implements Serializable {
    private static final long serialVersionUID = -1212xxxL;

    private String name;
    private String zipcode;
    private int distance;

    @Override
    public String toString() {
        return String.format("FindDocBean[name: %s, zipcode:%s, distance:%s]",
                name, zipcode, distance);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance = distance;
    }

As per all the suggestions found so far, they are suggesting to restrict the bean with required parameters only by something like below :

final String[] DISALLOWED_FIELDS = new String[]{"bean.name", "bean.zipcode", };

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setDisallowedFields(DISALLOWED_FIELDS);

But my problem is all the 3 parameters of the bean will be used in either of the method supplied on Controller.

Can someone please suggest some solution for this. Thanks in advance.

Answer

Mehmet Sunkur picture Mehmet Sunkur · Jan 2, 2018

InitBinder can be used for methods. You can try this.

@InitBinder("findDocByName")
public void initBinderByName(WebDataBinder binder) {
    binder.setDisallowedFields(new String[]{"distance","zipcode"});
}


@InitBinder("findDocByLocation")
public void initBinderByZipCode(WebDataBinder binder) {
    binder.setDisallowedFields(new String[]{"distance","name"});
}