secguide icon indicating copy to clipboard operation
secguide copied to clipboard

#java# 规范 1.9.1 条修订建议

Open k4n5ha0 opened this issue 3 years ago • 0 comments

1、问题描述 java 代码安全规范的【1.9.1 条】 返回信息最小化 需补充

2、解决建议 应补充下列编码规范: 解决方案1:

@Controller
class UserController {

	//禁止在url中使用业务变量,以防止篡改导致的越权
	@PostMapping("/user")
	public UserEntity getUser(@RequestParam("id") String id) {

	//返回用户所有字段内容,可能包括敏感字段
	return userService.findById(id).get(); 
	}
}

@Controller
class UserController {

	@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request){
		//限制返回给用户的字段
		binder.setAllowedFields(["username","password"]);
	}
}

解决方案2:

@Controller
class UserController {

	//禁止在url中使用业务变量,以防止篡改导致的越权
	@PostMapping("/user")
	public UserEntity getUser(@RequestParam("id") String id) {

	//返回用户所有字段内容,可能包括敏感字段
	return userService.findById(id).get(); 
	}
}

class UserEntity {

	@Id
	private Long id;
	private String username;

	// 如果使用jackson,可以使用@JsonIgnore禁止某字段参加格式化
	// 在某字段的get方法上使用@JsonIgnore对应禁止序列化,在set方法方法上使用@JsonIgnore对应禁止反序列化
	// 或者使用@JsonIgnoreProperties(value = "{password}")禁止某字段参与格式化
	@JsonIgnore
	private String password;
}

k4n5ha0 avatar May 24 '21 15:05 k4n5ha0