I am trying to setup an edit form for my User
object. I have automatic binding from the form to the user object working fine.
I'm wondering how do I prevent malicious users from binding to fields of my User
object that I don't want them to?
For example, my user object has userName
, and it also has points
. When they click edit user, I want them to be able to change the userName
, but not the points
. A malicious user could just send an extra points=429429
as a hidden field in the form by editing the HTML, and this would automatically be bound to the backing object by开发者_如何转开发 Spring.
I would suggest separating your front-end code from the logic for what will be saved in the database. The form backing object is just meant to be a simple object that captures want the user has done in the view... it shouldn't be used to save directly to the database. I would have a Service layer handle the decision on whether or not to update certain fields... the controller should just receive the input and pass it along. This way, the service can decide what fields should be updated.
public void updateUser(long userId, User updatedUser) {
User currentUser = dao.getCurrentUserById(userId);
currentUser.userName = updatedUser.username;
//...... update anyother fields....
dao.SaveUser(currentUser);
}
or you could define the method in a way that the caller knows what will be updated:
public void updateUser(long userId, String updatedUsername);
I would also argue that this is a lot easier to unit test if this logic is in the Service Layer.
Hope this helps
Add this to your controller:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setAllowedFields("field1", "field2");
}
精彩评论