- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的测试(我包括了两个类以查看其中一个是否可以工作)都没有调用 Controller 的问题。我希望它因 CORS 问题而被拒绝,因为我没有添加任何 CORS 配置。 (然后我想使用 CORS 配置进行测试并通过)。
如何强制 CORS 失败?
第一次尝试:
import com.testing.Application;
import com.testing.config.ControllerConfig;
import com.testing.controller.MyController;
import com.testing.dto.TestDateResponse;
import com.testing.exception.GlobalExceptionHandler;
import com.testing.service.TestService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import java.time.LocalDate;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class TestCORS
{
@Autowired
private ConfigurableWebApplicationContext context;
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@InjectMocks
private MyController myController;
@Autowired
private RestTemplate restTemplate;
@Before
public void setup()
{
//Initialize our injected mocks
MockitoAnnotations.initMocks(this);
//Create a controller
myController = new MyController( new TestService(), restTemplate );
//Create an environment for it
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.dispatchOptions(true)
.build();
//Create our marshaller
objectMapper = new ObjectMapper();
}
/**
* Tests that we fail when trying to access cross origin
* @throws Exception if json unmarshaller cannot parse the response
*/
@Test
public void testValidRequest() throws Exception
{
String request = "{\"asOfDate\":\"20170210\"}";
//Call to test a date
ResultActions actions = mockMvc.perform(
post("/v1/testdate")
.contentType(MediaType.APPLICATION_JSON)
.content(request)
//CORS HEADERS
.header("Access-Control-Request-Method", "DELETE")
.header("Origin", "https://evil.com")
);
actions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
TestDateResponse response = objectMapper.readValue(actions.andReturn().getResponse().getContentAsString(), TestDateResponse.class);
assertThat(response, notNullValue());
// verify date has returned back correctly
assertThat(response.getRetDate(), equalTo(LocalDate.of(2017, 02, 10)));
}
}
第二次尝试:
import com.testing.config.ControllerConfig;
import com.testing.controller.MyController;
import com.testing.dto.TestDateResponse;
import com.testing.exception.GlobalExceptionHandler;
import com.testing.service.TestService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ControllerConfig.class})
public class TestCORS
{
private MockMvc mockMvc;
private ObjectMapper objectMapper;
private MyController myController;
@Autowired
private RestTemplate restTemplate;
@Before
public void setup()
{
//Initialize our injected mocks
MockitoAnnotations.initMocks(this);
//Create a controller
myController = new MyController( new TestService(), restTemplate );
//Create an environment for it
mockMvc = MockMvcBuilders.standaloneSetup(myController)
.setControllerAdvice(new GlobalExceptionHandler())
.build();
//Create our marshaller
objectMapper = new ObjectMapper();
}
/**
* Tests that we fail when trying to access cross origin
* @throws Exception if json unmarshaller cannot parse the response
*/
@Test
public void testValidRequest() throws Exception
{
String request = "{\"asOfDate\":\"20170210\"}";
//Call to test a date
ResultActions actions = mockMvc.perform(
post("/v1/testdate")
.contentType(MediaType.APPLICATION_JSON)
.content(request)
//CORS HEADERS
.header("Access-Control-Request-Method", "GET")
.header("Origin", "http://www.someurl.com")
);
actions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
TestDateResponse response = objectMapper.readValue(actions.andReturn().getResponse().getContentAsString(), TestDateResponse.class);
assertThat(response, notNullValue());
// verify date has returned back correctly
assertThat(response.getRetDate(), equalTo(LocalDate.of(2017, 02, 10)));
}
}
最佳答案
CORS 不是那样工作的。
要检查 CORS,必须对 URL 进行预检调用。这不是 POST,而是针对具有 CORS header 的相同 URL 的 OPTIONS 请求。
通过该调用,无论是否允许实际调用(针对 DELETE),您都将收到 CORS 响应。
类似的东西应该可以工作:
ResultActions actions = mockMvc.perform(
options("/v1/testdate")
.contentType(MediaType.APPLICATION_JSON)
//CORS HEADERS
.header("Access-Control-Request-Method", "DELETE")
.header("Origin", "https://evil.com")
);
然后简单地断言预期的响应头。
关于spring - 如何在 Spring Boot 中测试 CORS?当我在 MockMvcBuilders 中尝试时,它总是返回 200,尽管 Origin 是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677740/
我尝试访问此 API click here for more info POST https://api.line.me/v2/oauth/accessToken 但总是得到错误: XMLHttpRe
我在掌握 CORS 概念时遇到问题... 我认为同源策略保护应用程序不会对“不受信任的域”进行 ajax 调用。所以, mydomain.com 向 发出 ajax 调用somedomain.com
一个技术性很强的问题,可能只有了解浏览器内部结构的人才能回答...... 浏览器缓存 CORS 预检响应的准确程度如何(假设在对 OPTIONS 预检请求的响应中返回了 Access-Control-
我一直在阅读 CORS以及它是如何工作的,但我发现很多事情令人困惑。例如,有很多关于事情的细节,比如 User Joe is using browser BrowserX to get data fr
在 OWASP site 上看到这个矛盾,我感到很困惑。 CORS 备忘单: 使用 Access-Control-Allow-Credentials: true 响应 header 时要特别小心。将允
我们无法在飞行前恢复使用 cors:任何帮助都非常感谢 ==========错误========================== About to connect() to localhost p
跨域请求字体文件时,您必须确保允许请求域使用 CORS header 访问字体文件: 访问控制允许来源 访问控制允许凭据 然而,这在请求图像时不是必需的,无论是对于 img元素或 background
CORS 规范没有说明服务器应如何响应无效的 CORS 请求。例如,如果请求 Origin 无效,则 CORS spec states :“终止这组步骤。请求超出了本规范的范围。”其他错误情况也有类似
我在理解同源策略和“解决”它的不同方法时遇到了一些麻烦。 很明显,同源策略是作为一种安全措施而存在的,因此来自服务器/域的一个脚本无法访问来自另一个服务器/域的数据。 也很明显,有时能够打破此规则很有
我正在尝试使用 cloudformation 在 API Gateway 中部署 API。这些方法需要启用 CORS,我遵循此处的模板 Enable CORS for API Gateway in C
我正在构建一个使用 CORS 的 REST 应用程序。每个 REST 调用都是不同的,我发现获取预检 OPTIONS 调用会产生很大的开销。有没有办法缓存并应用预检选项结果,以便对同一域的任何后续调用
我正在将我的 WebApi 升级到 MVC6。 在 WebApi 中,我可以拦截每个 HTTP 请求,如果是预检,我可以用浏览器可以接受的 header 进行响应。 我正在尝试找出如何在 MVC6 W
假设一个 CORS 预检请求进来了,但它为一个或多个 Access-Control-Request-* 指定了一个不受支持的值。标题。服务器应该如何将其传达回浏览器? 一些例子: 浏览器发送带有 Ac
问题中的一切。 附加信息: 使用 Win 10,GraphDB 免费,9.1.1 • RDF4J 3.0.1 • Connectors 12.0.2 我在控制台 => 设置中添加了 graphdb.w
我正在尝试通过 jQuery 调用 Sonar 网络服务之一。由于调用是跨域进行的,因此调用在 Chrome 上失败并出现以下错误: 请求的资源上不存在“Access-Control-Allow-Or
我想使用 NestJs api,但我在每个 fetch 中都收到相同的错误消息: Access to fetch at 'http://localhost:3000/articles' from or
我不确定这是否属于这里,但我在开发我的 svelte 应用程序时遇到了问题。 在开发过程中,它目前在独立服务器上运行(遵循使用 rollup 和 sirv 的指南)并针对不同端口上的后端 API。 稍
如果在服务器上正确设置 CORS 以仅允许某些来源访问服务器,这是否足以防止 XSRF 攻击? 最佳答案 更具体地说,很容易错误地认为如果 evil.com 由于 CORS 无法向 good.com
我在 Istio 入口上启用 CORS 时遇到问题。正如 Istio Ingress 文档所述,“ingresskubernetes.io”注释将被忽略。是否可以在 Istio 入口上启用 CORS?
我在 Istio 入口上启用 CORS 时遇到问题。正如 Istio Ingress 文档所述,“ingresskubernetes.io”注释将被忽略。是否可以在 Istio 入口上启用 CORS?
我是一名优秀的程序员,十分优秀!