From b3d87492735abfb6da6d5230ad8d6c7a19832be6 Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Thu, 30 Nov 2017 14:19:45 -0800 Subject: [PATCH] #326 - Extend CORS examples. Add examples for preflight- and rejected requests. --- .../rest/headers/CustomerRepository.java | 6 +++--- .../headers/CrossOriginIntegrationTests.java | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/rest/headers/src/main/java/example/springdata/rest/headers/CustomerRepository.java b/rest/headers/src/main/java/example/springdata/rest/headers/CustomerRepository.java index bf61f768..af909575 100644 --- a/rest/headers/src/main/java/example/springdata/rest/headers/CustomerRepository.java +++ b/rest/headers/src/main/java/example/springdata/rest/headers/CustomerRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 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. @@ -20,10 +20,10 @@ import org.springframework.web.bind.annotation.CrossOrigin; /** * Spring Data repository interface to manage {@link Customer} instances. - * + * * @author Oliver Gierke * @author Mark Paluch * @soundtrack The Intersphere - Out of phase (Live at Alte Feuerwache Mannheim) */ -@CrossOrigin +@CrossOrigin(origins = { "http://localhost", "http://localhost:1234" }) public interface CustomerRepository extends CrudRepository {} diff --git a/rest/headers/src/test/java/example/springdata/rest/headers/CrossOriginIntegrationTests.java b/rest/headers/src/test/java/example/springdata/rest/headers/CrossOriginIntegrationTests.java index 8f53ec8f..c66075ee 100644 --- a/rest/headers/src/test/java/example/springdata/rest/headers/CrossOriginIntegrationTests.java +++ b/rest/headers/src/test/java/example/springdata/rest/headers/CrossOriginIntegrationTests.java @@ -51,6 +51,18 @@ public class CrossOriginIntegrationTests { this.mvc = MockMvcBuilders.webAppContextSetup(context).build(); } + @Test + public void executePreflightRequest() throws Exception { + + String origin = "http://localhost:1234"; + URI uri = URI.create("/customers"); + + mvc.perform(options(uri).header(ORIGIN, origin).header(ACCESS_CONTROL_REQUEST_METHOD, "POST")) // + .andExpect(header().string(ACCESS_CONTROL_ALLOW_ORIGIN, is(origin))) // + .andExpect(header().string(ACCESS_CONTROL_ALLOW_METHODS, containsString("GET"))) // + .andExpect(header().string(ACCESS_CONTROL_ALLOW_METHODS, containsString("POST"))); // + } + @Test public void executeCrossOriginRequest() throws Exception { @@ -62,4 +74,13 @@ public class CrossOriginIntegrationTests { .andExpect(header().string(ACCESS_CONTROL_ALLOW_ORIGIN, is(origin))); } + @Test + public void rejectCrossOriginRequest() throws Exception { + + String origin = "http://foo.bar"; + URI uri = URI.create("/customers"); + + mvc.perform(get(uri).header(ORIGIN, origin)) // + .andExpect(status().isForbidden()); + } }