因三方测试扫描出了安全渗透问题,需要修改springboot默认的返回值信息
前期:Spring Boot 2.2.5.RELEASE 并且引入了 WebSocket
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
import java.util.Map;
@Component
public class CustomErrorAttributes implements ErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new java.util.HashMap<>();
// 通过 WebRequest 获取异常对象
Throwable error = getError(webRequest);
// 获取状态码
Integer status = (Integer) webRequest.getAttribute("javax.servlet.error.status_code", RequestAttributes.SCOPE_REQUEST);
// 获取请求路径
String path = (String) webRequest.getAttribute("javax.servlet.error.request_uri", RequestAttributes.SCOPE_REQUEST);
// 获取当前时间戳
long timestamp = System.currentTimeMillis();
// 错误类型(如果有的话)
String errorType = error != null ? error.getClass().getSimpleName() : "UnknownError";
// 填充 errorAttributes
errorAttributes.put("timestamp", new Date(timestamp)); // 当前时间戳
errorAttributes.put("status", status != null ? status : 500); // 错误状态码(默认500)
errorAttributes.put("error", errorType); // 错误类型(例如 NullPointerException)
errorAttributes.put("message", error != null ? error.getMessage() : "未知错误"); // 错误信息
errorAttributes.put("path", path != null ? path : "未知路径"); // 错误发生的请求路径
// 针对 405 错误的自定义处理
if (status != null && status == 405) {
errorAttributes.put("message", "自定义的405错误信息:请求方法不被允许。");
}
return errorAttributes;
}
@Override
public Throwable getError(WebRequest webRequest) {
// 获取 WebRequest 中的异常对象
return (Throwable) webRequest.getAttribute(RequestAttributes.ATTRIBUTE_ERROR_EXCEPTION, RequestAttributes.SCOPE_REQUEST);
}
@Override
public String getErrorMessage(WebRequest webRequest) {
Throwable error = getError(webRequest);
return error != null ? error.getMessage() : "错误发生";
}
}
解释:
-
timestamp
:使用System.currentTimeMillis()
获取当前的时间戳,并将其转换为Date
对象。这个时间戳代表了错误发生的时刻。 -
status
:从WebRequest
中获取状态码。若状态码不存在,则默认为 500(服务器错误)。 -
error
:如果发生了异常,我们通过error.getClass().getSimpleName()
获取异常类的名称。例如,如果发生了NullPointerException
,则该字段的值将是"NullPointerException"
。如果没有异常,默认值是"UnknownError"
。 -
message
:如果是405
错误,我们返回自定义的错误信息"自定义的405错误信息:请求方法不被允许。"
, 否则返回异常的消息,如果没有异常,则返回"未知错误"
。 -
path
:从WebRequest
获取请求路径(即出错时的 URL),如果路径为空则使用"未知路径"
。
-
示例输出:
假设发生了
405
错误,返回的 JSON 错误信息将会类似于: -
{ "timestamp": "2024-11-21T07:31:22.123+0000", "status": 405, "error": "MethodNotAllowedException", "message": "自定义的405错误信息:请求方法不被允许。", "path": "/api/v1/resource" }
如果是其他错误(例如 500),返回的错误信息将会类似于:
-
{ "timestamp": "2024-11-21T07:32:45.678+0000", "status": 500, "error": "UnknownError", "message": "发生了未知错误", "path": "/api/v1/resource" }
这样,你就能在错误响应中包含更多有用的信息,例如时间戳、错误类型、错误消息和请求路径等。