在Spring Boot中禁用或模拟OAuth2进行集成测试
我试图在运行集成测试时禁用/模拟本地OAuth2服务器,但到目前为止,大多数方法都涉及SpringMVC,我没有使用它。这是最常见的解决方案:在Spring Boot中禁用或模拟OAuth2进行集成测试,spring,integration-testing,spring-security-oauth2,Spring,Integration Testing,Spring Security Oauth2,我试图在运行集成测试时禁用/模拟本地OAuth2服务器,但到目前为止,大多数方法都涉及SpringMVC,我没有使用它。这是最常见的解决方案: this.mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .apply(springSecurity()) .build(); 在Spring Boot上,我有一个用于端点请求的TestRe
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
在Spring Boot上,我有一个用于端点请求的TestRestTemplate
。我在考试中有这样一句话:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"eureka.client.enabled:false"})
public class ApiControllerTest {
@Test
@WithOauth2TestAuthentication
public void employeesPost() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer FOO");
headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
ResponseEntity<OperationResultDTO> responseEntity =
this.restTemplate.postForEntity("/employees", new HttpEntity<>(loggedEmployee, headers), OperationResultDTO.class);
assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode());
}
}
SecurityContextFactory:
public class WithOAuth2AuthenticationSecurityContextFactory
implements WithSecurityContextFactory<WithOauth2TestAuthentication> {
@Override
public SecurityContext createSecurityContext(WithOauth2TestAuthentication annotation) {
Set<String> scopes = new HashSet<>();
Collections.addAll(scopes, annotation.scopes());
OAuth2Request oAuth2Request = new OAuth2Request(null, annotation.clientId(),
null, true, scopes, null, null,
null, null);
Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request,
new TestingAuthenticationToken(annotation.username(), null, "read"));
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(auth2Authentication);
return context;
}
}
带有OAuth2AuthenticationSecurityContextFactory的公共类
使用SecurityContextFactory实现{
@凌驾
public SecurityContext createSecurityContext(带OAuth2TestAuthentication批注){
Set scopes=new HashSet();
Collections.addAll(scopes,annotation.scopes());
OAuth2Request OAuth2Request=新的OAuth2Request(null,annotation.clientId(),
null,true,scopes,null,null,
空,空);
Authentication auth2Authentication=新的OAuth2Authentication(oAuth2Request,
新的TestingAuthenticationToken(annotation.username(),null,“read”);
SecurityContext上下文=SecurityContextHolder.createEmptyContext();
setAuthentication(auth2Authentication);
返回上下文;
}
}
到目前为止,每次测试运行都会抛出一个断言错误,这意味着请求返回401而不是422,这正是我的目标。我试着用这些指令来伪装OAuth服务器:没有用(我也试图避免它,但我的拍摄没有成功)。我也可以模拟授权令牌,但我不确定在这里如何做。我最终做的是将OAuth2配置文件放在不同的
@Profile
上,为每个控制器测试创建一个抽象类,并将MockMvc与@AutoConfigureMockMvc
一起使用:
@AutoConfigureMockMvc
@SpringBootTest
@ActiveProfiles({ "default", "local", "test" })
abstract class BaseControllerTest {
}
@RunWith(SpringRunner.class)
public class SampleControllerTest extends BaseControllerTest {
@Autowired
private MockMvc mockMvc;
// ...
@Test
@WithMockUser
public void aTest() throws Exception {
MvcResult result =
mockMvc.perform(get(URL_TEMPLATE).with(csrf()))
.andExpect(status().isOk())
.andReturn();
}
}
通过这种设置,
SecurityContext
确实返回了一个模拟用户,这最终导致我的401 HTTP代码请求失败。如果我需要针对一个不可处理的实体响应,只需将status().isOk()
切换为status().isUnprocessableEntity()
我最后做的是将OAuth2配置文件放在不同的@Profile
上,并为每个控制器测试创建一个抽象类,并将MockMvc与@AutoConfigureMockMvc
一起使用:
@AutoConfigureMockMvc
@SpringBootTest
@ActiveProfiles({ "default", "local", "test" })
abstract class BaseControllerTest {
}
@RunWith(SpringRunner.class)
public class SampleControllerTest extends BaseControllerTest {
@Autowired
private MockMvc mockMvc;
// ...
@Test
@WithMockUser
public void aTest() throws Exception {
MvcResult result =
mockMvc.perform(get(URL_TEMPLATE).with(csrf()))
.andExpect(status().isOk())
.andReturn();
}
}
通过这种设置,
SecurityContext
确实返回了一个模拟用户,这最终导致我的401 HTTP代码请求失败。如果需要针对不可处理的实体响应,只需将status().isOk()
切换为status().isUnprocessableEntity()
找到解决方案了吗?找到解决方案了吗?