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 {
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<? extends Payload>[] payload() default {};
}

View File

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