forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCorsHandler.java
More file actions
194 lines (163 loc) · 5.71 KB
/
CorsHandler.java
File metadata and controls
194 lines (163 loc) · 5.71 KB
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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Handle preflight and simple CORS requests. CORS options are set via: {@link Cors}.
*
* @author edgar
* @since 2.0.4
* @see Cors
*/
public class CorsHandler implements Route.Decorator {
private static final String ORIGIN = "Origin";
private static final String ANY_ORIGIN = "*";
private static final String AC_REQUEST_METHOD = "Access-Control-Request-Method";
private static final String AC_REQUEST_HEADERS = "Access-Control-Request-Headers";
private static final String AC_MAX_AGE = "Access-Control-Max-Age";
private static final String AC_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
private static final String AC_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String AC_ALLOW_HEADERS = "Access-Control-Allow-Headers";
private static final String AC_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String AC_ALLOW_METHODS = "Access-Control-Allow-Methods";
private final Cors options;
private static final Logger log = LoggerFactory.getLogger(CorsHandler.class);
/**
* Creates a new {@link CorsHandler}.
*
* @param options Cors options, or empty for using default options.
*/
public CorsHandler(@Nonnull final Cors options) {
this.options = options;
}
/**
* Creates a new {@link CorsHandler} with default options.
*/
public CorsHandler() {
this(new Cors());
}
@Nonnull @Override public Route.Handler apply(@Nonnull Route.Handler next) {
return ctx -> {
String origin = ctx.header("Origin").valueOrNull();
if (origin != null) {
if (!options.allowOrigin(origin)) {
log.debug("denied origin: {}", origin);
return ctx.send(StatusCode.FORBIDDEN);
}
log.debug("allowed origin: {}", origin);
if (isPreflight(ctx)) {
log.debug("handling preflight for: {}", origin);
if (preflight(ctx, options, origin)) {
return ctx;
} else {
log.debug("preflight for {} {} with origin: {} failed", ctx.header(AC_REQUEST_METHOD),
ctx.getRequestURL(), origin);
return ctx.send(StatusCode.FORBIDDEN);
}
} else {
// OPTIONS?
if (ctx.getMethod().equalsIgnoreCase(Router.OPTIONS)) {
// handle normal OPTIONS
String allow = Router.METHODS.stream()
.flatMap(method -> allowMethod(ctx, method))
.collect(Collectors.joining(","));
ctx.setResponseHeader("Allow", allow);
return ctx.send(StatusCode.OK);
} else {
log.debug("handling simple cors for: {}", origin);
ctx.setResetHeadersOnError(false);
simple(ctx, options, origin);
}
}
}
return next.apply(ctx);
};
}
private Stream<String> allowMethod(Context ctx, String method) {
String existingMethod = ctx.getMethod();
try {
ctx.setMethod(method);
Router.Match match = ctx.getRouter().match(ctx);
return match.matches() ? Stream.of(method) : Stream.empty();
} finally {
ctx.setMethod(existingMethod);
}
}
private static void simple(final Context ctx, final Cors options, final String origin) {
if ("null".equals(origin)) {
ctx.setResponseHeader(AC_ALLOW_ORIGIN, ANY_ORIGIN);
} else {
ctx.setResponseHeader(AC_ALLOW_ORIGIN, origin);
if (!options.anyHeader()) {
ctx.setResponseHeader("Vary", ORIGIN);
}
if (options.getUseCredentials()) {
ctx.setResponseHeader(AC_ALLOW_CREDENTIALS, true);
}
if (!options.getExposedHeaders().isEmpty()) {
ctx.setResponseHeader(AC_EXPOSE_HEADERS,
options.getExposedHeaders().stream().collect(Collectors.joining()));
}
}
}
@Nonnull @Override public void setRoute(@Nonnull Route route) {
route.setHttpOptions(true);
}
private boolean isPreflight(final Context ctx) {
return ctx.getMethod().equals(Router.OPTIONS) && !ctx.header(AC_REQUEST_METHOD).isMissing();
}
private boolean preflight(final Context ctx, final Cors options, final String origin) {
/*
Allowed method
*/
boolean allowMethod = ctx.header(AC_REQUEST_METHOD).toOptional()
.map(options::allowMethod)
.orElse(false);
if (!allowMethod) {
return false;
}
/*
Allowed headers
*/
List<String> headers = ctx.header(AC_REQUEST_HEADERS).toOptional().map(header ->
Arrays.asList(header.split("\\s*,\\s*"))
).orElse(Collections.emptyList());
if (!options.allowHeaders(headers)) {
return false;
}
/*
Allowed methods
*/
ctx.setResponseHeader(AC_ALLOW_METHODS,
options.getMethods().stream().collect(Collectors.joining(",")));
List<String> allowedHeaders = options.anyHeader() ? headers : options.getHeaders();
ctx.setResponseHeader(AC_ALLOW_HEADERS,
allowedHeaders.stream().collect(Collectors.joining(",")));
/*
Allow credentials
*/
if (options.getUseCredentials()) {
ctx.setResponseHeader(AC_ALLOW_CREDENTIALS, true);
}
long maxAge = options.getMaxAge().getSeconds();
if (maxAge > 0) {
ctx.setResponseHeader(AC_MAX_AGE, maxAge);
}
ctx.setResponseHeader(AC_ALLOW_ORIGIN, origin);
if (!options.anyOrigin()) {
ctx.setResponseHeader("Vary", ORIGIN);
}
ctx.send(StatusCode.OK);
return true;
}
}