参数校验和加密:对用户请求中的参数进行严格校验,防止用户通过修改参数来访问其他用户的数据。例如,对于订单查询接口,对订单号进行加密处理,并且在后端解密后验证订单号是否与当前登录用户匹配。同时,对用户输入的参数进行合法性检查,如数据类型、范围等。在一个Java Spring Boot应用中,使用@Valid
注解对请求参数进行校验:
import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/orders") public class OrderController { @GetMapping("/{encryptedOrderId}") public ResponseEntity<Order> getOrder(@PathVariable("encryptedOrderId") String encryptedOrderId, @Valid OrderQueryRequest request, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } // 解密订单号并验证是否与用户匹配 String orderId = decryptOrderId(encryptedOrderId); if (!isOrderIdValidForUser(orderId, request.getUser())) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } Order order = orderService.getOrder(orderId); return new ResponseEntity<>(order, HttpStatus.OK); } }