在Spring Boot中禁用或模拟OAuth2进行集成测试

时间:2017-06-27 15:51:16

标签: spring integration-testing spring-security-oauth2

我正在尝试在运行集成测试时禁用/模拟本地OAuth2服务器,但到目前为止,大多数方法都涉及Spring MVC,我没有使用它。这是最常见的解决方案:

 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());
}
}

注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
@WithSecurityContext(factory = WithOAuth2AuthenticationSecurityContextFactory.class)
public @interface WithOauth2TestAuthentication {
    String clientId() default "temporal";

    String username() default "username";

    String[] scopes() default { "read", "write", "trust" };
}

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;
}
}

到目前为止,每次测试都会向我抛出一个断言错误,这意味着请求返回401而不是422,这正是我的目标。我尝试使用这些说明伪造OAuth服务器:http://engineering.pivotal.io/post/faking_oauth_sso/无济于事(我也试图避免它,但我的镜头没有成功)。我也可以嘲笑授权令牌,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我最终做的是将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()