/
CorsConfiguration.java
465 lines (418 loc) · 14.3 KB
/
CorsConfiguration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.cors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* A container for CORS configuration along with methods to check against the
* actual origin, HTTP methods, and headers of a given request.
*
* <p>By default a newly created {@code CorsConfiguration} does not permit any
* cross-origin requests and must be configured explicitly to indicate what
* should be allowed. Use {@link #applyPermitDefaultValues()} to flip the
* initialization model to start with open defaults that permit all cross-origin
* requests for GET, HEAD, and POST requests.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sam Brannen
* @since 4.2
* @see <a href="https://www.w3.org/TR/cors/">CORS spec</a>
*/
public class CorsConfiguration {
/** Wildcard representing <em>all</em> origins, methods, or headers. */
public static final String ALL = "*";
private static final List<HttpMethod> DEFAULT_METHODS;
static {
List<HttpMethod> rawMethods = new ArrayList<HttpMethod>(2);
rawMethods.add(HttpMethod.GET);
rawMethods.add(HttpMethod.HEAD);
DEFAULT_METHODS = Collections.unmodifiableList(rawMethods);
}
private List<String> allowedOrigins;
private List<String> allowedMethods;
private List<HttpMethod> resolvedMethods = DEFAULT_METHODS;
private List<String> allowedHeaders;
private List<String> exposedHeaders;
private Boolean allowCredentials;
private Long maxAge;
/**
* Construct a new {@code CorsConfiguration} instance with no cross-origin
* requests allowed for any origin by default.
* @see #applyPermitDefaultValues()
*/
public CorsConfiguration() {
}
/**
* Construct a new {@code CorsConfiguration} instance by copying all
* values from the supplied {@code CorsConfiguration}.
*/
public CorsConfiguration(CorsConfiguration other) {
this.allowedOrigins = other.allowedOrigins;
this.allowedMethods = other.allowedMethods;
this.resolvedMethods = other.resolvedMethods;
this.allowedHeaders = other.allowedHeaders;
this.exposedHeaders = other.exposedHeaders;
this.allowCredentials = other.allowCredentials;
this.maxAge = other.maxAge;
}
/**
* Set the origins to allow, e.g. {@code "https://domain1.com"}.
* <p>The special value {@code "*"} allows all domains.
* <p>By default this is not set.
* <p><strong>Note:</strong> CORS checks use values from "Forwarded"
* (<a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>),
* "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" headers,
* if present, in order to reflect the client-originated address.
* Consider using the {@code ForwardedHeaderFilter} in order to choose from a
* central place whether to extract and use, or to discard such headers.
* See the Spring Framework reference for more on this filter.
*/
public void setAllowedOrigins(List<String> allowedOrigins) {
this.allowedOrigins = (allowedOrigins != null ? new ArrayList<String>(allowedOrigins) : null);
}
/**
* Return the configured origins to allow, or {@code null} if none.
* @see #addAllowedOrigin(String)
* @see #setAllowedOrigins(List)
*/
public List<String> getAllowedOrigins() {
return this.allowedOrigins;
}
/**
* Add an origin to allow.
*/
public void addAllowedOrigin(String origin) {
if (this.allowedOrigins == null) {
this.allowedOrigins = new ArrayList<String>(4);
}
this.allowedOrigins.add(origin);
}
/**
* Set the HTTP methods to allow, e.g. {@code "GET"}, {@code "POST"},
* {@code "PUT"}, etc.
* <p>The special value {@code "*"} allows all methods.
* <p>If not set, only {@code "GET"} and {@code "HEAD"} are allowed.
* <p>By default this is not set.
*/
public void setAllowedMethods(List<String> allowedMethods) {
this.allowedMethods = (allowedMethods != null ? new ArrayList<String>(allowedMethods) : null);
if (!CollectionUtils.isEmpty(allowedMethods)) {
this.resolvedMethods = new ArrayList<HttpMethod>(allowedMethods.size());
for (String method : allowedMethods) {
if (ALL.equals(method)) {
this.resolvedMethods = null;
break;
}
this.resolvedMethods.add(HttpMethod.resolve(method));
}
}
else {
this.resolvedMethods = DEFAULT_METHODS;
}
}
/**
* Return the allowed HTTP methods, or {@code null} in which case
* only {@code "GET"} and {@code "HEAD"} allowed.
* @see #addAllowedMethod(HttpMethod)
* @see #addAllowedMethod(String)
* @see #setAllowedMethods(List)
*/
public List<String> getAllowedMethods() {
return this.allowedMethods;
}
/**
* Add an HTTP method to allow.
*/
public void addAllowedMethod(HttpMethod method) {
if (method != null) {
addAllowedMethod(method.name());
}
}
/**
* Add an HTTP method to allow.
*/
public void addAllowedMethod(String method) {
if (StringUtils.hasText(method)) {
if (this.allowedMethods == null) {
this.allowedMethods = new ArrayList<String>(4);
this.resolvedMethods = new ArrayList<HttpMethod>(4);
}
this.allowedMethods.add(method);
if (ALL.equals(method)) {
this.resolvedMethods = null;
}
else if (this.resolvedMethods != null) {
this.resolvedMethods.add(HttpMethod.resolve(method));
}
}
}
/**
* Set the list of headers that a pre-flight request can list as allowed
* for use during an actual request.
* <p>The special value {@code "*"} allows actual requests to send any
* header.
* <p>A header name is not required to be listed if it is one of:
* {@code Cache-Control}, {@code Content-Language}, {@code Expires},
* {@code Last-Modified}, or {@code Pragma}.
* <p>By default this is not set.
*/
public void setAllowedHeaders(List<String> allowedHeaders) {
this.allowedHeaders = (allowedHeaders != null ? new ArrayList<String>(allowedHeaders) : null);
}
/**
* Return the allowed actual request headers, or {@code null} if none.
* @see #addAllowedHeader(String)
* @see #setAllowedHeaders(List)
*/
public List<String> getAllowedHeaders() {
return this.allowedHeaders;
}
/**
* Add an actual request header to allow.
*/
public void addAllowedHeader(String allowedHeader) {
if (this.allowedHeaders == null) {
this.allowedHeaders = new ArrayList<String>(4);
}
this.allowedHeaders.add(allowedHeader);
}
/**
* Set the list of response headers other than simple headers (i.e.
* {@code Cache-Control}, {@code Content-Language}, {@code Content-Type},
* {@code Expires}, {@code Last-Modified}, or {@code Pragma}) that an
* actual response might have and can be exposed.
* <p>Note that {@code "*"} is not a valid exposed header value.
* <p>By default this is not set.
*/
public void setExposedHeaders(List<String> exposedHeaders) {
if (exposedHeaders != null && exposedHeaders.contains(ALL)) {
throw new IllegalArgumentException("'*' is not a valid exposed header value");
}
this.exposedHeaders = (exposedHeaders != null ? new ArrayList<String>(exposedHeaders) : null);
}
/**
* Return the configured response headers to expose, or {@code null} if none.
* @see #addExposedHeader(String)
* @see #setExposedHeaders(List)
*/
public List<String> getExposedHeaders() {
return this.exposedHeaders;
}
/**
* Add a response header to expose.
* <p>Note that {@code "*"} is not a valid exposed header value.
*/
public void addExposedHeader(String exposedHeader) {
if (ALL.equals(exposedHeader)) {
throw new IllegalArgumentException("'*' is not a valid exposed header value");
}
if (this.exposedHeaders == null) {
this.exposedHeaders = new ArrayList<String>(4);
}
this.exposedHeaders.add(exposedHeader);
}
/**
* Whether user credentials are supported.
* <p>By default this is not set (i.e. user credentials are not supported).
*/
public void setAllowCredentials(Boolean allowCredentials) {
this.allowCredentials = allowCredentials;
}
/**
* Return the configured {@code allowCredentials} flag, or {@code null} if none.
* @see #setAllowCredentials(Boolean)
*/
public Boolean getAllowCredentials() {
return this.allowCredentials;
}
/**
* Configure how long, in seconds, the response from a pre-flight request
* can be cached by clients.
* <p>By default this is not set.
*/
public void setMaxAge(Long maxAge) {
this.maxAge = maxAge;
}
/**
* Return the configured {@code maxAge} value, or {@code null} if none.
* @see #setMaxAge(Long)
*/
public Long getMaxAge() {
return this.maxAge;
}
/**
* By default a newly created {@code CorsConfiguration} does not permit any
* cross-origin requests and must be configured explicitly to indicate what
* should be allowed.
* <p>Use this method to flip the initialization model to start with open
* defaults that permit all cross-origin requests for GET, HEAD, and POST
* requests. Note however that this method will not override any existing
* values already set.
* <p>The following defaults are applied if not already set:
* <ul>
* <li>Allow all origins.</li>
* <li>Allow "simple" methods {@code GET}, {@code HEAD} and {@code POST}.</li>
* <li>Allow all headers.</li>
* <li>Set max age to 1800 seconds (30 minutes).</li>
* </ul>
*/
public CorsConfiguration applyPermitDefaultValues() {
if (this.allowedOrigins == null) {
this.addAllowedOrigin(ALL);
}
if (this.allowedMethods == null) {
this.setAllowedMethods(Arrays.asList(
HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name()));
}
if (this.allowedHeaders == null) {
this.addAllowedHeader(ALL);
}
if (this.maxAge == null) {
this.setMaxAge(1800L);
}
return this;
}
/**
* Combine the supplied {@code CorsConfiguration} with this one.
* <p>Properties of this configuration are overridden by any non-null
* properties of the supplied one.
* @return the combined {@code CorsConfiguration} or {@code this}
* configuration if the supplied configuration is {@code null}
*/
public CorsConfiguration combine(CorsConfiguration other) {
if (other == null) {
return this;
}
CorsConfiguration config = new CorsConfiguration(this);
config.setAllowedOrigins(combine(getAllowedOrigins(), other.getAllowedOrigins()));
config.setAllowedMethods(combine(getAllowedMethods(), other.getAllowedMethods()));
config.setAllowedHeaders(combine(getAllowedHeaders(), other.getAllowedHeaders()));
config.setExposedHeaders(combine(getExposedHeaders(), other.getExposedHeaders()));
Boolean allowCredentials = other.getAllowCredentials();
if (allowCredentials != null) {
config.setAllowCredentials(allowCredentials);
}
Long maxAge = other.getMaxAge();
if (maxAge != null) {
config.setMaxAge(maxAge);
}
return config;
}
private List<String> combine(List<String> source, List<String> other) {
if (other == null || other.contains(ALL)) {
return source;
}
if (source == null || source.contains(ALL)) {
return other;
}
Set<String> combined = new LinkedHashSet<String>(source);
combined.addAll(other);
return new ArrayList<String>(combined);
}
/**
* Check the origin of the request against the configured allowed origins.
* @param requestOrigin the origin to check
* @return the origin to use for the response, or {@code null} which
* means the request origin is not allowed
*/
public String checkOrigin(String requestOrigin) {
if (!StringUtils.hasText(requestOrigin)) {
return null;
}
if (ObjectUtils.isEmpty(this.allowedOrigins)) {
return null;
}
if (this.allowedOrigins.contains(ALL)) {
if (this.allowCredentials != Boolean.TRUE) {
return ALL;
}
else {
return requestOrigin;
}
}
for (String allowedOrigin : this.allowedOrigins) {
if (requestOrigin.equalsIgnoreCase(allowedOrigin)) {
return requestOrigin;
}
}
return null;
}
/**
* Check the HTTP request method (or the method from the
* {@code Access-Control-Request-Method} header on a pre-flight request)
* against the configured allowed methods.
* @param requestMethod the HTTP request method to check
* @return the list of HTTP methods to list in the response of a pre-flight
* request, or {@code null} if the supplied {@code requestMethod} is not allowed
*/
public List<HttpMethod> checkHttpMethod(HttpMethod requestMethod) {
if (requestMethod == null) {
return null;
}
if (this.resolvedMethods == null) {
return Collections.singletonList(requestMethod);
}
return (this.resolvedMethods.contains(requestMethod) ? this.resolvedMethods : null);
}
/**
* Check the supplied request headers (or the headers listed in the
* {@code Access-Control-Request-Headers} of a pre-flight request) against
* the configured allowed headers.
* @param requestHeaders the request headers to check
* @return the list of allowed headers to list in the response of a pre-flight
* request, or {@code null} if none of the supplied request headers is allowed
*/
public List<String> checkHeaders(List<String> requestHeaders) {
if (requestHeaders == null) {
return null;
}
if (requestHeaders.isEmpty()) {
return Collections.emptyList();
}
if (ObjectUtils.isEmpty(this.allowedHeaders)) {
return null;
}
boolean allowAnyHeader = this.allowedHeaders.contains(ALL);
List<String> result = new ArrayList<String>(requestHeaders.size());
for (String requestHeader : requestHeaders) {
if (StringUtils.hasText(requestHeader)) {
requestHeader = requestHeader.trim();
if (allowAnyHeader) {
result.add(requestHeader);
}
else {
for (String allowedHeader : this.allowedHeaders) {
if (requestHeader.equalsIgnoreCase(allowedHeader)) {
result.add(requestHeader);
break;
}
}
}
}
}
return (result.isEmpty() ? null : result);
}
}