java - XSS攻击: change exception thrown in a Spring Boot CRUDRepository ?

标签 java spring spring-boot exception xss

我正在为一个应用程序开发一个 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/

相关文章:

java - sendKeys 不适用于与 Appium 和 Java 一起使用的输入(三星的数字键盘)

spring - 更改分支后无法解决Flyway依赖性

java - 使用 spring 和 mongodb 根据我的查询获取文档列表

spring - 使用 Spring Data JPA 进行延迟获取

java - 如何在Spring中注册FactoryBeans集合

spring-boot - Spring Boot Web 服务器在 Eclipse 中运行良好,无法在服务器 : missing EmbeddedServletContainerFactory bean 上启动

java - 用户名的正则表达式会增加 CPU 消耗

java - 如何使用java将timestamp-millis logicalType序列化为avro文件

java - 如何让 IntelliJ 使用 Java7 作为 Google App Engine 开发服务器?

java - spring @RequestParam Unicode 不正确