Play framework 2 (Java) form data binding with nested allowed fields

牧云@^-^@ 提交于 2019-12-02 02:04:41

Here's an arguably simpler solution. How about defining an extra constraint that will trigger a validation failure if the POST data contains any informations[%d].securedField values?

import javax.validation.constraints.Null;

public static class Information {

    @Null
    public String securedField;

    ...

}

I think that this way you can call the default bindFromRequest method instead of the one that accepts a whitelist of form field names, and still be protected against a mass assignment attack.

One shortcoming with this approach admittedly is that it would ultimately leak the names of your internal fields in the event of a concerted mass assignment attack. However if they had fairly bland, meaningless names such as securedField (no offence intended!), I'm not sure how this information could be exploited by an attacker.

Edit

If you want to allow assignment to the field based on the current user type, maybe bean validation groups could help:

import javax.validation.constraints.Null;

public class Contact {

    public interface Administrator {}

    public interface User {}

    ...

    public class Information {

        @Null(groups = User.class)
        public String securedField;

        ...

    }

}

Controller code

...
final Form<Contact> contactForm;
if (currentUser.isAdministrator()) {
    contactForm = form(Contact.class, Administrator.class).bindFromRequest();
} else {
    contactForm = form(Contact.class, User.class).bindFromRequest();
}
...

If I understand your question correctly, you can use the following patterns to whitelist nested collection fields:

informations[*].email
informations[*].phones[*].*

i.e.

form.bindFromRequest("name", "informations[*].email", "informations[*].phones[*].*");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!