Reject requests with a body but no Content-Type header

This commit is contained in:
Paul Trudel 2024-04-18 10:58:22 -04:00
parent 8e40d91877
commit e24e358ddd
2 changed files with 3 additions and 2 deletions

View File

@ -16,7 +16,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
public @interface ContentTypeConstraint { public @interface ContentTypeConstraint {
String key() default "contentTypeError"; String key() default "contentTypeError";
String message() default "Request content type is not supported"; String message() default "Request content type is not supported or no Content-Type header was specified";
Class<?>[] groups() default {}; Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {}; Class<? extends Payload>[] payload() default {};
} }

View File

@ -28,11 +28,12 @@ public class ContentTypeValidator implements ConstraintValidator<ContentTypeCons
public boolean isValid(HttpServletRequest request, ConstraintValidatorContext context) { public boolean isValid(HttpServletRequest request, ConstraintValidatorContext context) {
String requestMethod = request.getMethod(); String requestMethod = request.getMethod();
String contentType = request.getContentType(); String contentType = request.getContentType();
String contentTypeHeader = request.getHeader("Content-Type");
log.info("Validating {} request with content type {}", requestMethod, contentType); log.info("Validating {} request with content type {}", requestMethod, contentType);
boolean requestBodyPresent = request.getContentLength() > 0; boolean requestBodyPresent = request.getContentLength() > 0;
if (requestBodyPresent) { if (requestBodyPresent) {
if (contentType == null) return false; if (contentType == null || contentTypeHeader == null) return false;
else { else {
return SUPPORTED_CONTENT_TYPES.contains(contentType); return SUPPORTED_CONTENT_TYPES.contains(contentType);
} }