Skip to content

Commit

Permalink
fixes #26 add method access for cors
Browse files Browse the repository at this point in the history
  • Loading branch information
stevehu committed Feb 18, 2017
1 parent cca420d commit 8aa2fdf
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 6 deletions.
5 changes: 5 additions & 0 deletions cors/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@
<artifactId>undertow-core</artifactId>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
9 changes: 9 additions & 0 deletions cors/src/main/java/com/networknt/cors/CorsConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
public class CorsConfig {
boolean enabled;
List allowedOrigins;
List allowedMethods;

@JsonIgnore
String description;
Expand All @@ -33,6 +34,14 @@ public void setAllowedOrigins(List allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}

public List getAllowedMethods() {
return allowedMethods;
}

public void setAllowedMethods(List allowedMethods) {
this.allowedMethods = allowedMethods;
}

public String getDescription() {
return description;
}
Expand Down
8 changes: 2 additions & 6 deletions cors/src/main/java/com/networknt/cors/CorsHttpHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public class CorsHttpHandler implements MiddlewareHandler {
(CorsConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, CorsConfig.class);

private static final Collection<String> allowedOrigins = config.getAllowedOrigins();
private static final Collection<String> allowedMethods = config.getAllowedMethods();

private volatile HttpHandler next;
/** Default max age **/
Expand Down Expand Up @@ -93,12 +94,7 @@ private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exceptio
exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
}
}
HeaderValues requestedMethods = headers.get(ACCESS_CONTROL_REQUEST_METHOD);
if (requestedMethods != null && !requestedMethods.isEmpty()) {
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, requestedMethods);
} else {
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, Arrays.asList(new String[]{Methods.GET_STRING, Methods.POST_STRING}));
}
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods);
HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
Expand Down
5 changes: 5 additions & 0 deletions cors/src/main/resources/config/cors.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
"enabled": true,
"allowedOrigins": [
"http://localhost"
],
"allowedMethods": [
"GET",
"POST",
"PUT"
]
}
126 changes: 126 additions & 0 deletions cors/src/test/main/java/com/networknt/cors/CorsHttpHandlerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package com.networknt.cors;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;
import io.undertow.util.Methods;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
* Created by stevehu on 2017-02-17.
*/
public class CorsHttpHandlerTest {
static final Logger logger = LoggerFactory.getLogger(CorsHttpHandlerTest.class);

static Undertow server = null;

@BeforeClass
public static void setUp() {
if(server == null) {
logger.info("starting server");
HttpHandler handler = getTestHandler();
CorsHttpHandler corsHttpHandler = new CorsHttpHandler();
corsHttpHandler.setNext(handler);
handler = corsHttpHandler;
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(handler)
.build();
server.start();
}
}

@AfterClass
public static void tearDown() throws Exception {
if(server != null) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {

}
server.stop();
logger.info("The server is stopped.");
}
}

static RoutingHandler getTestHandler() {
return Handlers.routing()
.add(Methods.GET, "/", exchange -> {
exchange.getResponseSender().send("OK");
})
.add(Methods.POST, "/", exchange -> {
exchange.getResponseSender().send("OK");
});
}

@Test
public void testOptionsWrongOrigin() throws Exception {
String url = "http://localhost:8080";
CloseableHttpClient client = HttpClients.createDefault();
HttpOptions httpOptions = new HttpOptions(url);
httpOptions.setHeader("Origin", "http://example.com");
httpOptions.setHeader("Access-Control-Request-Method", "POST");
httpOptions.setHeader("Access-Control-Request-Headers", "X-Requested-With");

try {
CloseableHttpResponse response = client.execute(httpOptions);
int statusCode = response.getStatusLine().getStatusCode();
String body = IOUtils.toString(response.getEntity().getContent(), "utf8");
Header header = response.getFirstHeader("Access-Control-Allow-Origin");
Assert.assertEquals(200, statusCode);
if(statusCode == 200) {
Assert.assertNull(header);
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Test
public void testOptionsCorrectOrigin() throws Exception {
String url = "http://localhost:8080";
CloseableHttpClient client = HttpClients.createDefault();
HttpOptions httpOptions = new HttpOptions(url);
httpOptions.setHeader("Origin", "http://localhost");
httpOptions.setHeader("Access-Control-Request-Method", "POST");
httpOptions.setHeader("Access-Control-Request-Headers", "X-Requested-With");

try {
CloseableHttpResponse response = client.execute(httpOptions);
int statusCode = response.getStatusLine().getStatusCode();
String body = IOUtils.toString(response.getEntity().getContent(), "utf8");
Header header = response.getFirstHeader("Access-Control-Allow-Origin");
Assert.assertEquals(200, statusCode);
if(statusCode == 200) {
Assert.assertNotNull(header);
}
} catch (Exception e) {
e.printStackTrace();
}
}

}
11 changes: 11 additions & 0 deletions cors/src/test/resources/config/cors.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"description": "Cors Http Handler",
"enabled": true,
"allowedOrigins": [
"http://localhost"
],
"allowedMethods": [
"GET",
"POST"
]
}

0 comments on commit 8aa2fdf

Please sign in to comment.