我正在为一个应用程序开发一个 API,该应用程序能够根据解决方案 ID(这是一个整数)找到所谓的 ProductSolutions。
代码如下所示:
@Repository
public interface ProductSolutionRepository extends CrudRepository<ProductSolution, String> {
public List<ProductSolution> findBySolutionId(@Param("solutionId") int solutionId);
}
当使用字符串而不是整数发送请求时 (localhost:8080/api/v1/productSolutions/search/findBySolutionId?solutionId=dangerousscript
),API 将返回错误并显示以下消息:
Failed to convert from type [java.lang.String] to type [@org.springframework.data.repository.query.Param int] for value 'dangerousscript'; nested exception is java.lang.NumberFormatException: For input string: \"dangerousscript\""`
尽管 Chrome 和 Firefox 似乎巧妙地转义了输入(并且不执行任何脚本),但人们仍然担心我们的 API 可能会被用于跨站点脚本攻击。
解决此问题的一个简单方法是删除用户在引发异常时提供的输入,或者创建自己的错误页面。我可以通过什么方式配置spring boot来抛出自定义异常?
最佳答案
您可以在使用 @ControllerAdvice
注解的类中使用 @ExceptionHandler
定义方法。
您可以使用@ResponseBody
注释此方法(如果您没有使用@RestController
)并直接返回所需的响应或使用正确的消息重新抛出异常。
@ControllerAdvice
public class RestExceptionControllerAdvice {
@ExceptionHandler(NumberFormatException.class)
public ErrorResponse handleSearchParseException(NumberFormatException exception) {
// do whathever you want
}
}
关于java - XSS攻击: change exception thrown in a Spring Boot CRUDRepository ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46343384/