在Spring中使用setAllowedFields()方法


问题内容

我正在使用Spring 3.2.0。我已经为一些基本需求注册了一些自定义属性编辑器,如下所示。

import editors.DateTimeEditor;
import editors.StrictNumberFormatEditor;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.joda.time.DateTime;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.propertyeditors.URLEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public final class GlobalDataBinder 
{
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request)
    {
        binder.setIgnoreInvalidFields(true);
        binder.setIgnoreUnknownFields(true);
        //binder.setAllowedFields(someArray);
        NumberFormat numberFormat=DecimalFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);

        binder.registerCustomEditor(DateTime.class, new DateTimeEditor("MM/dd/yyyy HH:mm:ss", true));
        binder.registerCustomEditor(Double.class, new StrictNumberFormatEditor(Double.class, numberFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(URL.class, new URLEditor());
    } 
}

到目前为止,我已经注册了这么多编辑器。其中两个DateTimeEditorStrictNumberFormatEditor已经通过覆盖相应的方法,以满足数字格式和定制需求定制乔达时间

由于我使用的是Spring
3.2.0,因此可以利用@ControllerAdvice

Spring建议使用该setAllowedFields()方法列出一组允许的字段,以使恶意用户无法将值注入绑定的对象。

文档有关DataBinder

允许将属性值设置到目标对象上的活页夹,包括对验证和绑定结果分析的支持。可以通过指定允许的字段,必填字段,自定义编辑器等来自定义绑定过程。

请注意,如果无法设置允许字段的数组,可能会带来安全隐患。例如,在使用HTTP表单POST数据的情况下,恶意客户端可以通过提供表单上不存在的字段或属性的值来尝试破坏应用程序。在某些情况下,这可能会导致在命令对象或其嵌套对象上设置非法数据。因此,
强烈建议allowedFields在DataBinder上
指定 属性


我的应用程序很大,显然有数千个字段。用指定和列出所有这些setAllowedFields()都是繁琐的工作。此外,我需要以某种方式记住它们。

更改网页以删除某些字段或在需要时添加其他字段需要再次修改方法的参数值setAllowedFields()以反映这些更改。

除此之外,还有其他选择吗?


问题答案:

除了使用setAllowedFields()白名单,您还可以使用setDisallowedFields()黑名单。例如,从petclinic示例应用程序中:

@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
    dataBinder.setDisallowedFields("id");
}

从纯粹的安全角度来看,白名单比黑名单更可取,但它可能会减轻一些负担。