Check if the given origin matches the origin of the request. @param request The HTTP servlet request @param origin The origin to check @return True if the origin matches the request's origin
(HttpServletRequest request, String origin)
| 139 | * @return True if the origin matches the request's origin |
| 140 | */ |
| 141 | public static boolean isSameOrigin(HttpServletRequest request, String origin) { |
| 142 | // Build scheme://host:port from request |
| 143 | StringBuilder target = new StringBuilder(); |
| 144 | String scheme = request.getScheme(); |
| 145 | String host = request.getServerName(); |
| 146 | if (scheme == null || host == null) { |
| 147 | return false; |
| 148 | } |
| 149 | scheme = scheme.toLowerCase(Locale.ENGLISH); |
| 150 | target.append(scheme).append("://").append(host); |
| 151 | |
| 152 | int port = request.getServerPort(); |
| 153 | // Origin may or may not include the (default) port. |
| 154 | // At this point target doesn't include a port. |
| 155 | if (target.length() == origin.length()) { |
| 156 | // origin and target can only be equal if both are using default |
| 157 | // ports. Therefore, only append the port to the target if a |
| 158 | // non-default port is used. |
| 159 | if (("http".equals(scheme) || "ws".equals(scheme)) && port != 80 || |
| 160 | ("https".equals(scheme) || "wss".equals(scheme)) && port != 443) { |
| 161 | target.append(':'); |
| 162 | target.append(port); |
| 163 | } |
| 164 | } else { |
| 165 | // origin and target can only be equal if: |
| 166 | // a) origin includes an explicit default port |
| 167 | // b) origin is using a non-default port |
| 168 | // Either way, add the port to the target so it can be compared |
| 169 | target.append(':'); |
| 170 | target.append(port); |
| 171 | } |
| 172 | |
| 173 | |
| 174 | // Both scheme and host are case-insensitive but the CORS spec states |
| 175 | // this check should be case-sensitive |
| 176 | return origin.contentEquals(target); |
| 177 | } |
| 178 | |
| 179 | |
| 180 | /** |