1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package waffle.util;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29
30 import javax.servlet.http.HttpServletRequest;
31
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35
36
37
38 public final class CorsPreFlightCheck {
39
40
41 private static final Logger LOGGER = LoggerFactory.getLogger(CorsPreFlightCheck.class);
42
43
44 private static final String PRE_FLIGHT_ATTRIBUTE_VALUE = "PRE_FLIGHT";
45
46
47 private static final List<String> CORS_PRE_FLIGHT_HEADERS = new ArrayList<>(
48 Arrays.asList("Access-Control-Request-Method", "Access-Control-Request-Headers", "Origin"));
49
50
51
52
53 private CorsPreFlightCheck() {
54
55 }
56
57
58
59
60
61
62
63
64
65 public static boolean isPreflight(final HttpServletRequest request) {
66
67 final String corsRequestType = (String) request.getAttribute("cors.request.type");
68
69 CorsPreFlightCheck.LOGGER
70 .debug("[waffle.util.CorsPreflightCheck] Request is CORS preflight; continue filter chain");
71
72
73 final String method = request.getMethod();
74 if (method == null || !method.equalsIgnoreCase("OPTIONS")) {
75 return false;
76 }
77
78 CorsPreFlightCheck.LOGGER.debug("[waffle.util.CorsPreflightCheck] check for PRE_FLIGHT Attribute");
79
80
81
82
83 if (corsRequestType != null
84 && corsRequestType.equalsIgnoreCase(CorsPreFlightCheck.PRE_FLIGHT_ATTRIBUTE_VALUE)) {
85 return true;
86 } else {
87
88
89
90
91 CorsPreFlightCheck.LOGGER.debug("[waffle.util.CorsPreflightCheck] check headers");
92
93 for (final String header : CorsPreFlightCheck.CORS_PRE_FLIGHT_HEADERS) {
94 final String headerValue = request.getHeader(header);
95 CorsPreFlightCheck.LOGGER.debug("[waffle.util.CorsPreflightCheck] {}", header);
96
97 if (headerValue == null) {
98
99 return false;
100 }
101 }
102 CorsPreFlightCheck.LOGGER.debug("[waffle.util.CorsPreflightCheck] is preflight");
103
104 return true;
105 }
106 }
107 }