在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());
}
}
到目前为止,我已经注册了这么多编辑.其中两个DateTimeEditor和StrictNumberFormatEditor已通过覆盖各自的方法来定制,以满足数字格式和Joda-Time的自定义需求.
由于我使用的是Spring 3.2.0,我可以利用@ControllerAdvice
.
Spring建议使用setAllowedFields()
方法列出一组允许的字段,以便恶意用户无法将值注入绑定对象.
从docs开始,关于DataBinder
Binder that allows for setting property values onto a target object,
including support for validation and binding result analysis. The
binding process can be customized through specifying allowed fields,
required fields, custom editors, etc.Note that there are potential security implications in failing to set
an array of allowed fields. In the case of HTTP form POST data for
example, malicious clients can attempt to subvert an application by
supplying values for fields or properties that do not exist on the
form. In some cases this could lead to illegal data being set on
command objects or their nested objects. For this reason, it is highly
recommended to specify the 07004 property on the DataBinder.
我有一个很大的应用程序,显然有成千上万的领域.使用setAllowedFields()
指定和列出所有这些是一项繁琐的工作.另外,不知怎的,我需要记住它们.
根据需要更改网页以删除某些字段或添加其他字段需要修改setAllowedFields()
方法的参数值以反映这些更改.
有没有替代方案?
解决方法:
您可以将setDisallowedFields()用于黑名单,而不是将setAllowedFields()用于白名单.例如,来自petclinic样本应用程序:
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
从纯粹的安全角度来看,白名单比黑名单更受欢迎,但它可能有助于缓解一些负担.
标签:spring,spring-mvc,spring-3,databinder,propertyeditor 来源: https://codeday.me/bug/20191008/1872950.html