001/* 002 * Copyright 2002-2020 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.cors; 018 019import java.io.IOException; 020import java.nio.charset.Charset; 021import java.util.ArrayList; 022import java.util.List; 023import javax.servlet.http.HttpServletRequest; 024import javax.servlet.http.HttpServletResponse; 025 026import org.apache.commons.logging.Log; 027import org.apache.commons.logging.LogFactory; 028 029import org.springframework.http.HttpHeaders; 030import org.springframework.http.HttpMethod; 031import org.springframework.http.HttpStatus; 032import org.springframework.http.server.ServerHttpRequest; 033import org.springframework.http.server.ServerHttpResponse; 034import org.springframework.http.server.ServletServerHttpRequest; 035import org.springframework.http.server.ServletServerHttpResponse; 036import org.springframework.util.CollectionUtils; 037import org.springframework.web.util.WebUtils; 038 039/** 040 * The default implementation of {@link CorsProcessor}, as defined by the 041 * <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>. 042 * 043 * <p>Note that when input {@link CorsConfiguration} is {@code null}, this 044 * implementation does not reject simple or actual requests outright but simply 045 * avoid adding CORS headers to the response. CORS processing is also skipped 046 * if the response already contains CORS headers, or if the request is detected 047 * as a same-origin one. 048 * 049 * @author Sebastien Deleuze 050 * @author Rossen Stoyanchev 051 * @since 4.2 052 */ 053public class DefaultCorsProcessor implements CorsProcessor { 054 055 private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); 056 057 private static final Log logger = LogFactory.getLog(DefaultCorsProcessor.class); 058 059 060 @Override 061 @SuppressWarnings("resource") 062 public boolean processRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) 063 throws IOException { 064 065 if (!CorsUtils.isCorsRequest(request)) { 066 return true; 067 } 068 069 ServletServerHttpResponse serverResponse = new ServletServerHttpResponse(response); 070 if (responseHasCors(serverResponse)) { 071 logger.debug("Skip CORS processing: response already contains \"Access-Control-Allow-Origin\" header"); 072 return true; 073 } 074 075 ServletServerHttpRequest serverRequest = new ServletServerHttpRequest(request); 076 if (WebUtils.isSameOrigin(serverRequest)) { 077 logger.debug("Skip CORS processing: request is from same origin"); 078 return true; 079 } 080 081 boolean preFlightRequest = CorsUtils.isPreFlightRequest(request); 082 if (config == null) { 083 if (preFlightRequest) { 084 rejectRequest(serverResponse); 085 return false; 086 } 087 else { 088 return true; 089 } 090 } 091 092 return handleInternal(serverRequest, serverResponse, config, preFlightRequest); 093 } 094 095 private boolean responseHasCors(ServerHttpResponse response) { 096 try { 097 return (response.getHeaders().getAccessControlAllowOrigin() != null); 098 } 099 catch (NullPointerException npe) { 100 // SPR-11919 and https://issues.jboss.org/browse/WFLY-3474 101 return false; 102 } 103 } 104 105 /** 106 * Invoked when one of the CORS checks failed. 107 * The default implementation sets the response status to 403 and writes 108 * "Invalid CORS request" to the response. 109 */ 110 protected void rejectRequest(ServerHttpResponse response) throws IOException { 111 response.setStatusCode(HttpStatus.FORBIDDEN); 112 response.getBody().write("Invalid CORS request".getBytes(UTF8_CHARSET)); 113 } 114 115 /** 116 * Handle the given request. 117 */ 118 protected boolean handleInternal(ServerHttpRequest request, ServerHttpResponse response, 119 CorsConfiguration config, boolean preFlightRequest) throws IOException { 120 121 String requestOrigin = request.getHeaders().getOrigin(); 122 String allowOrigin = checkOrigin(config, requestOrigin); 123 124 HttpMethod requestMethod = getMethodToUse(request, preFlightRequest); 125 List<HttpMethod> allowMethods = checkMethods(config, requestMethod); 126 127 List<String> requestHeaders = getHeadersToUse(request, preFlightRequest); 128 List<String> allowHeaders = checkHeaders(config, requestHeaders); 129 130 if (allowOrigin == null || allowMethods == null || (preFlightRequest && allowHeaders == null)) { 131 rejectRequest(response); 132 return false; 133 } 134 135 HttpHeaders responseHeaders = response.getHeaders(); 136 responseHeaders.setAccessControlAllowOrigin(allowOrigin); 137 responseHeaders.add(HttpHeaders.VARY, HttpHeaders.ORIGIN); 138 139 if (preFlightRequest) { 140 responseHeaders.setAccessControlAllowMethods(allowMethods); 141 } 142 143 if (preFlightRequest && !allowHeaders.isEmpty()) { 144 responseHeaders.setAccessControlAllowHeaders(allowHeaders); 145 } 146 147 if (!CollectionUtils.isEmpty(config.getExposedHeaders())) { 148 responseHeaders.setAccessControlExposeHeaders(config.getExposedHeaders()); 149 } 150 151 if (Boolean.TRUE.equals(config.getAllowCredentials())) { 152 responseHeaders.setAccessControlAllowCredentials(true); 153 } 154 155 if (preFlightRequest && config.getMaxAge() != null) { 156 responseHeaders.setAccessControlMaxAge(config.getMaxAge()); 157 } 158 159 response.flush(); 160 return true; 161 } 162 163 /** 164 * Check the origin and determine the origin for the response. The default 165 * implementation simply delegates to 166 * {@link org.springframework.web.cors.CorsConfiguration#checkOrigin(String)}. 167 */ 168 protected String checkOrigin(CorsConfiguration config, String requestOrigin) { 169 return config.checkOrigin(requestOrigin); 170 } 171 172 /** 173 * Check the HTTP method and determine the methods for the response of a 174 * pre-flight request. The default implementation simply delegates to 175 * {@link org.springframework.web.cors.CorsConfiguration#checkHttpMethod(HttpMethod)}. 176 */ 177 protected List<HttpMethod> checkMethods(CorsConfiguration config, HttpMethod requestMethod) { 178 return config.checkHttpMethod(requestMethod); 179 } 180 181 private HttpMethod getMethodToUse(ServerHttpRequest request, boolean isPreFlight) { 182 return (isPreFlight ? request.getHeaders().getAccessControlRequestMethod() : request.getMethod()); 183 } 184 185 /** 186 * Check the headers and determine the headers for the response of a 187 * pre-flight request. The default implementation simply delegates to 188 * {@link org.springframework.web.cors.CorsConfiguration#checkOrigin(String)}. 189 */ 190 protected List<String> checkHeaders(CorsConfiguration config, List<String> requestHeaders) { 191 return config.checkHeaders(requestHeaders); 192 } 193 194 private List<String> getHeadersToUse(ServerHttpRequest request, boolean isPreFlight) { 195 HttpHeaders headers = request.getHeaders(); 196 return (isPreFlight ? headers.getAccessControlRequestHeaders() : new ArrayList<String>(headers.keySet())); 197 } 198 199}