use of io.micronaut.http.HttpAttributes.AVAILABLE_HTTP_METHODS in project micronaut-core by micronaut-projects.
the class CorsFilter method handleRequest.
/**
* Handles a CORS {@link HttpRequest}.
*
* @param request The {@link HttpRequest} object
* @return An optional {@link MutableHttpResponse}. The request should proceed normally if empty
*/
protected Optional<MutableHttpResponse<?>> handleRequest(HttpRequest request) {
HttpHeaders headers = request.getHeaders();
Optional<String> originHeader = headers.getOrigin();
if (originHeader.isPresent()) {
String requestOrigin = originHeader.get();
boolean preflight = CorsUtil.isPreflightRequest(request);
Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);
if (optionalConfig.isPresent()) {
CorsOriginConfiguration config = optionalConfig.get();
HttpMethod requestMethod = request.getMethod();
List<HttpMethod> allowedMethods = config.getAllowedMethods();
HttpMethod methodToMatch = preflight ? headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, CONVERSION_CONTEXT_HTTP_METHOD).orElse(requestMethod) : requestMethod;
if (!isAnyMethod(allowedMethods)) {
if (allowedMethods.stream().noneMatch(method -> method.equals(methodToMatch))) {
return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
}
}
Optional<? extends ArrayList<HttpMethod>> availableHttpMethods = (Optional<? extends ArrayList<HttpMethod>>) request.getAttribute(AVAILABLE_HTTP_METHODS, new ArrayList<HttpMethod>().getClass());
if (preflight && availableHttpMethods.isPresent() && availableHttpMethods.get().stream().anyMatch(method -> method.equals(methodToMatch))) {
Optional<List<String>> accessControlHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, ConversionContext.LIST_OF_STRING);
List<String> allowedHeaders = config.getAllowedHeaders();
if (!isAny(allowedHeaders) && accessControlHeaders.isPresent()) {
if (!accessControlHeaders.get().stream().allMatch(header -> allowedHeaders.stream().anyMatch(allowedHeader -> allowedHeader.equalsIgnoreCase(header.trim())))) {
return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
}
}
MutableHttpResponse<Object> ok = HttpResponse.ok();
handleResponse(request, ok);
return Optional.of(ok);
}
}
}
return Optional.empty();
}
Aggregations